diff --git a/.dev_scripts/diff_images.py b/.dev_scripts/diff_images.py index e21cae214e..5208ed41ec 100644 --- a/.dev_scripts/diff_images.py +++ b/.dev_scripts/diff_images.py @@ -20,13 +20,13 @@ def calc_images_mean_L1(image1_path, image2_path): def parse_args(): parser = argparse.ArgumentParser() - parser.add_argument('image1_path') - parser.add_argument('image2_path') + parser.add_argument("image1_path") + parser.add_argument("image2_path") args = parser.parse_args() return args -if __name__ == '__main__': +if __name__ == "__main__": args = parse_args() mean_L1 = calc_images_mean_L1(args.image1_path, args.image2_path) print(mean_L1) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 5afd17b417..c6b833cf58 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -1 +1,2 @@ b3dccfaeb636599c02effc377cdd8a87d658256c +218b6d0546b990fc449c876fb99f44b50c4daa35 diff --git a/.github/workflows/style-checks.yml b/.github/workflows/style-checks.yml new file mode 100644 index 0000000000..8aceb6469e --- /dev/null +++ b/.github/workflows/style-checks.yml @@ -0,0 +1,27 @@ +name: Black # TODO: add isort and flake8 later + +on: + pull_request: {} + push: + branches: master + tags: "*" + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Setup Python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + + - name: Install dependencies with pip + run: | + pip install --upgrade pip wheel + pip install .[test] + + # - run: isort --check-only . + - run: black --check . + # - run: flake8 diff --git a/.gitignore b/.gitignore index b7b5c1ae75..cc000de20e 100644 --- a/.gitignore +++ b/.gitignore @@ -38,7 +38,6 @@ develop-eggs/ downloads/ eggs/ .eggs/ -lib/ lib64/ parts/ sdist/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000000..2b16b274d6 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,10 @@ +# See https://pre-commit.com/ for usage and config +repos: +- repo: local + hooks: + - id: black + name: black + stages: [commit] + language: system + entry: black + types: [python] diff --git a/LICENSE-ModelWeights.txt b/LICENSE-SD1+SD2.txt similarity index 100% rename from LICENSE-ModelWeights.txt rename to LICENSE-SD1+SD2.txt diff --git a/LICENSE-SDXL.txt b/LICENSE-SDXL.txt new file mode 100644 index 0000000000..05fbe3abb6 --- /dev/null +++ b/LICENSE-SDXL.txt @@ -0,0 +1,290 @@ +Copyright (c) 2023 Stability AI +CreativeML Open RAIL++-M License dated July 26, 2023 + +Section I: PREAMBLE + +Multimodal generative models are being widely adopted and used, and +have the potential to transform the way artists, among other +individuals, conceive and benefit from AI or ML technologies as a tool +for content creation. + +Notwithstanding the current and potential benefits that these +artifacts can bring to society at large, there are also concerns about +potential misuses of them, either due to their technical limitations +or ethical considerations. + +In short, this license strives for both the open and responsible +downstream use of the accompanying model. When it comes to the open +character, we took inspiration from open source permissive licenses +regarding the grant of IP rights. Referring to the downstream +responsible use, we added use-based restrictions not permitting the +use of the model in very specific scenarios, in order for the licensor +to be able to enforce the license in case potential misuses of the +Model may occur. At the same time, we strive to promote open and +responsible research on generative models for art and content +generation. + +Even though downstream derivative versions of the model could be +released under different licensing terms, the latter will always have +to include - at minimum - the same use-based restrictions as the ones +in the original license (this license). We believe in the intersection +between open and responsible AI development; thus, this agreement aims +to strike a balance between both in order to enable responsible +open-science in the field of AI. + +This CreativeML Open RAIL++-M License governs the use of the model +(and its derivatives) and is informed by the model card associated +with the model. + +NOW THEREFORE, You and Licensor agree as follows: + +Definitions + +"License" means the terms and conditions for use, reproduction, and +Distribution as defined in this document. + +"Data" means a collection of information and/or content extracted from +the dataset used with the Model, including to train, pretrain, or +otherwise evaluate the Model. The Data is not licensed under this +License. + +"Output" means the results of operating a Model as embodied in +informational content resulting therefrom. + +"Model" means any accompanying machine-learning based assemblies +(including checkpoints), consisting of learnt weights, parameters +(including optimizer states), corresponding to the model architecture +as embodied in the Complementary Material, that have been trained or +tuned, in whole or in part on the Data, using the Complementary +Material. + +"Derivatives of the Model" means all modifications to the Model, works +based on the Model, or any other model which is created or initialized +by transfer of patterns of the weights, parameters, activations or +output of the Model, to the other model, in order to cause the other +model to perform similarly to the Model, including - but not limited +to - distillation methods entailing the use of intermediate data +representations or methods based on the generation of synthetic data +by the Model for training the other model. + +"Complementary Material" means the accompanying source code and +scripts used to define, run, load, benchmark or evaluate the Model, +and used to prepare data for training or evaluation, if any. This +includes any accompanying documentation, tutorials, examples, etc, if +any. + +"Distribution" means any transmission, reproduction, publication or +other sharing of the Model or Derivatives of the Model to a third +party, including providing the Model as a hosted service made +available by electronic or other remote means - e.g. API-based or web +access. + +"Licensor" means the copyright owner or entity authorized by the +copyright owner that is granting the License, including the persons or +entities that may have rights in the Model and/or distributing the +Model. + +"You" (or "Your") means an individual or Legal Entity exercising +permissions granted by this License and/or making use of the Model for +whichever purpose and in any field of use, including usage of the +Model in an end-use application - e.g. chatbot, translator, image +generator. + +"Third Parties" means individuals or legal entities that are not under +common control with Licensor or You. + +"Contribution" means any work of authorship, including the original +version of the Model and any modifications or additions to that Model +or Derivatives of the Model thereof, that is intentionally submitted +to Licensor for inclusion in the Model by the copyright owner or by an +individual or Legal Entity authorized to submit on behalf of the +copyright owner. For the purposes of this definition, "submitted" +means any form of electronic, verbal, or written communication sent to +the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control +systems, and issue tracking systems that are managed by, or on behalf +of, the Licensor for the purpose of discussing and improving the +Model, but excluding communication that is conspicuously marked or +otherwise designated in writing by the copyright owner as "Not a +Contribution." + +"Contributor" means Licensor and any individual or Legal Entity on +behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Model. + +Section II: INTELLECTUAL PROPERTY RIGHTS + +Both copyright and patent grants apply to the Model, Derivatives of +the Model and Complementary Material. The Model and Derivatives of the +Model are subject to additional terms as described in + +Section III. + +Grant of Copyright License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare, publicly display, publicly +perform, sublicense, and distribute the Complementary Material, the +Model, and Derivatives of the Model. + +Grant of Patent License. Subject to the terms and conditions of this +License and where and as applicable, each Contributor hereby grants to +You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this paragraph) patent license to +make, have made, use, offer to sell, sell, import, and otherwise +transfer the Model and the Complementary Material, where such license +applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by +combination of their Contribution(s) with the Model to which such +Contribution(s) was submitted. If You institute patent litigation +against any entity (including a cross-claim or counterclaim in a +lawsuit) alleging that the Model and/or Complementary Material or a +Contribution incorporated within the Model and/or Complementary +Material constitutes direct or contributory patent infringement, then +any patent licenses granted to You under this License for the Model +and/or Work shall terminate as of the date such litigation is asserted +or filed. + +Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION + +Distribution and Redistribution. You may host for Third Party remote +access purposes (e.g. software-as-a-service), reproduce and distribute +copies of the Model or Derivatives of the Model thereof in any medium, +with or without modifications, provided that You meet the following +conditions: Use-based restrictions as referenced in paragraph 5 MUST +be included as an enforceable provision by You in any type of legal +agreement (e.g. a license) governing the use and/or distribution of +the Model or Derivatives of the Model, and You shall give notice to +subsequent users You Distribute to, that the Model or Derivatives of +the Model are subject to paragraph 5. This provision does not apply to +the use of Complementary Material. You must give any Third Party +recipients of the Model or Derivatives of the Model a copy of this +License; You must cause any modified files to carry prominent notices +stating that You changed the files; You must retain all copyright, +patent, trademark, and attribution notices excluding those notices +that do not pertain to any part of the Model, Derivatives of the +Model. You may add Your own copyright statement to Your modifications +and may provide additional or different license terms and conditions - +respecting paragraph 4.a. - for use, reproduction, or Distribution of +Your modifications, or for any such Derivatives of the Model as a +whole, provided Your use, reproduction, and Distribution of the Model +otherwise complies with the conditions stated in this License. + +Use-based restrictions. The restrictions set forth in Attachment A are +considered Use-based restrictions. Therefore You cannot use the Model +and the Derivatives of the Model for the specified restricted +uses. You may use the Model subject to this License, including only +for lawful purposes and in accordance with the License. Use may +include creating any content with, finetuning, updating, running, +training, evaluating and/or reparametrizing the Model. You shall +require all of Your users who use the Model or a Derivative of the +Model to comply with the terms of this paragraph (paragraph 5). + +The Output You Generate. Except as set forth herein, Licensor claims +no rights in the Output You generate using the Model. You are +accountable for the Output you generate and its subsequent uses. No +use of the output can contravene any provision as stated in the +License. + +Section IV: OTHER PROVISIONS + +Updates and Runtime Restrictions. To the maximum extent permitted by +law, Licensor reserves the right to restrict (remotely or otherwise) +usage of the Model in violation of this License. + +Trademarks and related. Nothing in this License permits You to make +use of Licensors’ trademarks, trade names, logos or to otherwise +suggest endorsement or misrepresent the relationship between the +parties; and any rights not expressly granted herein are reserved by +the Licensors. + +Disclaimer of Warranty. Unless required by applicable law or agreed to +in writing, Licensor provides the Model and the Complementary Material +(and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +implied, including, without limitation, any warranties or conditions +of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +PARTICULAR PURPOSE. You are solely responsible for determining the +appropriateness of using or redistributing the Model, Derivatives of +the Model, and the Complementary Material and assume any risks +associated with Your exercise of permissions under this License. + +Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, unless +required by applicable law (such as deliberate and grossly negligent +acts) or agreed to in writing, shall any Contributor be liable to You +for damages, including any direct, indirect, special, incidental, or +consequential damages of any character arising as a result of this +License or out of the use or inability to use the Model and the +Complementary Material (including but not limited to damages for loss +of goodwill, work stoppage, computer failure or malfunction, or any +and all other commercial damages or losses), even if such Contributor +has been advised of the possibility of such damages. + +Accepting Warranty or Additional Liability. While redistributing the +Model, Derivatives of the Model and the Complementary Material +thereof, You may choose to offer, and charge a fee for, acceptance of +support, warranty, indemnity, or other liability obligations and/or +rights consistent with this License. However, in accepting such +obligations, You may act only on Your own behalf and on Your sole +responsibility, not on behalf of any other Contributor, and only if +You agree to indemnify, defend, and hold each Contributor harmless for +any liability incurred by, or claims asserted against, such +Contributor by reason of your accepting any such warranty or +additional liability. + +If any provision of this License is held to be invalid, illegal or +unenforceable, the remaining provisions shall be unaffected thereby +and remain valid as if such provision had not been set forth herein. + + +END OF TERMS AND CONDITIONS + +Attachment A + +Use Restrictions + +You agree not to use the Model or Derivatives of the Model: + +* In any way that violates any applicable national, federal, state, +local or international law or regulation; + +* For the purpose of exploiting, harming or attempting to exploit or +harm minors in any way; + +* To generate or disseminate verifiably false information and/or + content with the purpose of harming others; + +* To generate or disseminate personal identifiable information that + can be used to harm an individual; + +* To defame, disparage or otherwise harass others; + +* For fully automated decision making that adversely impacts an + individual’s legal rights or otherwise creates or modifies a + binding, enforceable obligation; + +* For any use intended to or which has the effect of discriminating + against or harming individuals or groups based on online or offline + social behavior or known or predicted personal or personality + characteristics; + +* To exploit any of the vulnerabilities of a specific group of persons + based on their age, social, physical or mental characteristics, in + order to materially distort the behavior of a person pertaining to + that group in a manner that causes or is likely to cause that person + or another person physical or psychological harm; + +* For any use intended to or which has the effect of discriminating + against individuals or groups based on legally protected + characteristics or categories; + +* To provide medical advice and medical results interpretation; + +* To generate or disseminate information for the purpose to be used + for administration of justice, law enforcement, immigration or + asylum processes, such as predicting an individual will commit + fraud/crime commitment (e.g. by text profiling, drawing causal + relationships between assertions made in documents, indiscriminate + and arbitrarily-targeted use). + diff --git a/README.md b/README.md index 6f6bd2a0b8..3ca1ca1f26 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,7 @@ and go to http://localhost:9090. ### Command-Line Installation (for developers and users familiar with Terminals) -You must have Python 3.9 or 3.10 installed on your machine. Earlier or +You must have Python 3.9 through 3.11 installed on your machine. Earlier or later versions are not supported. Node.js also needs to be installed along with yarn (can be installed with the command `npm install -g yarn` if needed) diff --git a/docs/features/CONFIGURATION.md b/docs/features/CONFIGURATION.md index ccb23ae79a..09e6143e95 100644 --- a/docs/features/CONFIGURATION.md +++ b/docs/features/CONFIGURATION.md @@ -65,7 +65,6 @@ InvokeAI: esrgan: true internet_available: true log_tokenization: false - nsfw_checker: false patchmatch: true restore: true ... @@ -138,7 +137,7 @@ command-line options by giving the `--help` argument: (.venv) > invokeai-web --help usage: InvokeAI [-h] [--host HOST] [--port PORT] [--allow_origins [ALLOW_ORIGINS ...]] [--allow_credentials | --no-allow_credentials] [--allow_methods [ALLOW_METHODS ...]] [--allow_headers [ALLOW_HEADERS ...]] [--esrgan | --no-esrgan] [--internet_available | --no-internet_available] [--log_tokenization | --no-log_tokenization] - [--nsfw_checker | --no-nsfw_checker] [--invisible_watermark | --no-invisible_watermark] [--patchmatch | --no-patchmatch] [--restore | --no-restore] + [--patchmatch | --no-patchmatch] [--restore | --no-restore] [--always_use_cpu | --no-always_use_cpu] [--free_gpu_mem | --no-free_gpu_mem] [--max_loaded_models MAX_LOADED_MODELS] [--max_cache_size MAX_CACHE_SIZE] [--max_vram_cache_size MAX_VRAM_CACHE_SIZE] [--gpu_mem_reserved GPU_MEM_RESERVED] [--precision {auto,float16,float32,autocast}] [--sequential_guidance | --no-sequential_guidance] [--xformers_enabled | --no-xformers_enabled] [--tiled_decode | --no-tiled_decode] [--root ROOT] @@ -175,8 +174,6 @@ These configuration settings allow you to enable and disable various InvokeAI fe | `esrgan` | `true` | Activate the ESRGAN upscaling options| | `internet_available` | `true` | When a resource is not available locally, try to fetch it via the internet | | `log_tokenization` | `false` | Before each text2image generation, print a color-coded representation of the prompt to the console; this can help understand why a prompt is not working as expected | -| `nsfw_checker` | `true` | Activate the NSFW checker to blur out risque images | -| `invisible_watermark` | `true` | Write an invisible watermark 'InvokeAI' into generated images for use by AI image detectors | | `patchmatch` | `true` | Activate the "patchmatch" algorithm for improved inpainting | | `restore` | `true` | Activate the facial restoration features (DEPRECATED; restoration features will be removed in 3.0.0) | diff --git a/docs/features/NSFW.md b/docs/features/WATERMARK+NSFW.md similarity index 62% rename from docs/features/NSFW.md rename to docs/features/WATERMARK+NSFW.md index f0539cc6a9..c837d66b57 100644 --- a/docs/features/NSFW.md +++ b/docs/features/WATERMARK+NSFW.md @@ -1,12 +1,40 @@ --- -title: The NSFW Checker +title: Watermarking, NSFW Image Checking --- -# :material-image-off: NSFW Checker +# :material-image-off: Invisible Watermark and the NSFW Checker + +## Watermarking + +InvokeAI does not apply watermarking to images by default. However, +many computer scientists working in the field of generative AI worry +that a flood of computer-generated imagery will contaminate the image +data sets needed to train future generations of generative models. + +InvokeAI offers an optional watermarking mode that writes a small bit +of text, **InvokeAI**, into each image that it generates using an +"invisible" watermarking library that spreads the information +throughout the image in a way that is not perceptible to the human +eye. If you are planning to share your generated images on +internet-accessible services, we encourage you to activate the +invisible watermark mode in order to help preserve the digital image +environment. + +The downside of watermarking is that it increases the size of the +image moderately, and has been reported by some individuals to degrade +image quality. Your mileage may vary. + +To read the watermark in an image, activate the InvokeAI virtual +environment (called the "developer's console" in the launcher) and run +the command: + +``` +invisible-watermark -a decode -t bytes -m dwtDct -l 64 /path/to/image.png +``` ## The NSFW ("Safety") Checker -The Stable Diffusion image generation models will produce sexual +Stable Diffusion 1.5-based image generation models will produce sexual imagery if deliberately prompted, and will occasionally produce such images when this is not intended. Such images are colloquially known as "Not Safe for Work" (NSFW). This behavior is due to the nature of @@ -18,35 +46,17 @@ jurisdictions it may be illegal to publicly distribute such imagery, including mounting a publicly-available server that provides unfiltered images to the public. Furthermore, the [Stable Diffusion weights -License](https://github.com/invoke-ai/InvokeAI/blob/main/LICENSE-ModelWeights.txt) -forbids the model from being used to "exploit any of the +License](https://github.com/invoke-ai/InvokeAI/blob/main/LICENSE-SD1+SD2.txt), +and the [Stable Diffusion XL +License][https://github.com/invoke-ai/InvokeAI/blob/main/LICENSE-SDXL.txt] +both forbid the models from being used to "exploit any of the vulnerabilities of a specific group of persons." For these reasons Stable Diffusion offers a "safety checker," a machine learning model trained to recognize potentially disturbing imagery. When a potentially NSFW image is detected, the checker will blur the image and paste a warning icon on top. The checker can be -turned on and off on the command line using `--nsfw_checker` and -`--no-nsfw_checker`. - -At installation time, InvokeAI will ask whether the checker should be -activated by default (neither argument given on the command line). The -response is stored in the InvokeAI initialization file -(`invokeai.yaml` in the InvokeAI root directory). You can change the -default at any time by opening this file in a text editor and -changing the line `nsfw_checker:` from true to false or vice-versa: - - -``` -... - Features: - esrgan: true - internet_available: true - log_tokenization: false - nsfw_checker: true - patchmatch: true - restore: true -``` +turned on and off in the Web interface under Settings. ## Caveats @@ -84,10 +94,3 @@ are encouraged to turn **off** intermediate image rendering when you are using the checker. Future versions of InvokeAI will apply additional blurring to intermediate images when the checker is active. -### Watermarking - -InvokeAI does not apply any sort of watermark to images it -generates. However, it does write metadata into the PNG data area, -including the prompt used to generate the image and relevant parameter -settings. These fields can be examined using the `sd-metadata.py` -script that comes with the InvokeAI package. diff --git a/docs/index.md b/docs/index.md index ce26f1f1f3..319df59bae 100644 --- a/docs/index.md +++ b/docs/index.md @@ -148,7 +148,7 @@ images in full-precision mode: - [Model Merging](features/MODEL_MERGING.md) - [ControlNet Models](features/CONTROLNET.md) - [Style/Subject Concepts and Embeddings](features/CONCEPTS.md) -- [Not Safe for Work (NSFW) Checker](features/NSFW.md) +- [Watermarking and the Not Safe for Work (NSFW) Checker](features/WATERMARK+NSFW.md) ### Prompt Engineering - [Prompt Syntax](features/PROMPTS.md) diff --git a/docs/installation/010_INSTALL_AUTOMATED.md b/docs/installation/010_INSTALL_AUTOMATED.md index 8072364b55..6eee9799f8 100644 --- a/docs/installation/010_INSTALL_AUTOMATED.md +++ b/docs/installation/010_INSTALL_AUTOMATED.md @@ -40,10 +40,8 @@ experimental versions later. this, open up a command-line window ("Terminal" on Linux and Macintosh, "Command" or "Powershell" on Windows) and type `python --version`. If Python is installed, it will print out the version - number. If it is version `3.9.*` or `3.10.*`, you meet - requirements. We do not recommend using Python 3.11 or higher, - as not all the libraries that InvokeAI depends on work properly - with this version. + number. If it is version `3.9.*`, `3.10.*` or `3.11.*` you meet + requirements. !!! warning "What to do if you have an unsupported version" @@ -215,17 +213,6 @@ experimental versions later. Generally the defaults are fine, and you can come back to this screen at any time to tweak your system. Here are the options you can adjust: - - ***Output directory for images*** - This is the path to a directory in which InvokeAI will store all its - generated images. - - - ***NSFW checker*** - If checked, InvokeAI will test images for potential sexual content - and blur them out if found. Note that the NSFW checker consumes - an additional 0.6 GB of VRAM on top of the 2-3 GB of VRAM used - by most image models. If you have a low VRAM GPU (4-6 GB), you - can reduce out of memory errors by disabling the checker. - - ***HuggingFace Access Token*** InvokeAI has the ability to download embedded styles and subjects from the HuggingFace Concept Library on-demand. However, some of @@ -257,20 +244,30 @@ experimental versions later. and graphics cards. The "autocast" option is deprecated and shouldn't be used unless you are asked to by a member of the team. - - ***Number of models to cache in CPU memory*** + - **Size of the RAM cache used for fast model switching*** This allows you to keep models in memory and switch rapidly among them rather than having them load from disk each time. This slider - controls how many models to keep loaded at once. Each - model will use 2-4 GB of RAM, so use this cautiously + controls how many models to keep loaded at once. A typical SD-1 or SD-2 model + uses 2-3 GB of memory. A typical SDXL model uses 6-7 GB. Providing more + RAM will allow more models to be co-resident. - - ***Directory containing embedding/textual inversion files*** - This is the directory in which you can place custom embedding - files (.pt or .bin). During startup, this directory will be - scanned and InvokeAI will print out the text terms that - are available to trigger the embeddings. + - ***Output directory for images*** + This is the path to a directory in which InvokeAI will store all its + generated images. + + - ***Autoimport Folder*** + This is the directory in which you can place models you have + downloaded and wish to load into InvokeAI. You can place a variety + of models in this directory, including diffusers folders, .ckpt files, + .safetensors files, as well as LoRAs, ControlNet and Textual Inversion + files (both folder and file versions). To help organize this folder, + you can create several levels of subfolders and drop your models into + whichever ones you want. + + - ***Autoimport FolderLICENSE*** At the bottom of the screen you will see a checkbox for accepting - the CreativeML Responsible AI License. You need to accept the license + the CreativeML Responsible AI Licenses. You need to accept the license in order to download Stable Diffusion models from the next screen. _You can come back to the startup options form_ as many times as you like. diff --git a/docs/installation/020_INSTALL_MANUAL.md b/docs/installation/020_INSTALL_MANUAL.md index 75309c5fea..c0fb4c046f 100644 --- a/docs/installation/020_INSTALL_MANUAL.md +++ b/docs/installation/020_INSTALL_MANUAL.md @@ -32,7 +32,7 @@ gaming): * **Python** - version 3.9 or 3.10 (3.11 is not recommended). + version 3.9 through 3.11 * **CUDA Tools** @@ -65,7 +65,7 @@ gaming): To install InvokeAI with virtual environments and the PIP package manager, please follow these steps: -1. Please make sure you are using Python 3.9 or 3.10. The rest of the install +1. Please make sure you are using Python 3.9 through 3.11. The rest of the install procedure depends on this and will not work with other versions: ```bash diff --git a/installer/install.sh.in b/installer/install.sh.in index 0063c0ebbf..1b8ba92ea6 100755 --- a/installer/install.sh.in +++ b/installer/install.sh.in @@ -9,16 +9,20 @@ cd $scriptdir function version { echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }'; } MINIMUM_PYTHON_VERSION=3.9.0 -MAXIMUM_PYTHON_VERSION=3.11.0 +MAXIMUM_PYTHON_VERSION=3.11.100 PYTHON="" -for candidate in python3.10 python3.9 python3 python ; do +for candidate in python3.11 python3.10 python3.9 python3 python ; do if ppath=`which $candidate`; then + # when using `pyenv`, the executable for an inactive Python version will exist but will not be operational + # we check that this found executable can actually run + if [ $($candidate --version &>/dev/null; echo ${PIPESTATUS}) -gt 0 ]; then continue; fi + python_version=$($ppath -V | awk '{ print $2 }') if [ $(version $python_version) -ge $(version "$MINIMUM_PYTHON_VERSION") ]; then - if [ $(version $python_version) -lt $(version "$MAXIMUM_PYTHON_VERSION") ]; then - PYTHON=$ppath - break - fi + if [ $(version $python_version) -le $(version "$MAXIMUM_PYTHON_VERSION") ]; then + PYTHON=$ppath + break + fi fi fi done diff --git a/installer/lib/installer.py b/installer/lib/installer.py index 5904a71968..e1ca8c2e8f 100644 --- a/installer/lib/installer.py +++ b/installer/lib/installer.py @@ -141,15 +141,16 @@ class Installer: # upgrade pip in Python 3.9 environments if int(platform.python_version_tuple()[1]) == 9: - from plumbum import FG, local pip = local[get_pip_from_venv(venv_dir)] - pip[ "install", "--upgrade", "pip"] & FG + pip["install", "--upgrade", "pip"] & FG return venv_dir - def install(self, root: str = "~/invokeai-3", version: str = "latest", yes_to_all=False, find_links: Path = None) -> None: + def install( + self, root: str = "~/invokeai-3", version: str = "latest", yes_to_all=False, find_links: Path = None + ) -> None: """ Install the InvokeAI application into the given runtime path @@ -175,7 +176,7 @@ class Installer: self.instance = InvokeAiInstance(runtime=self.dest, venv=self.venv, version=version) # install dependencies and the InvokeAI application - (extra_index_url,optional_modules) = get_torch_source() if not yes_to_all else (None,None) + (extra_index_url, optional_modules) = get_torch_source() if not yes_to_all else (None, None) self.instance.install( extra_index_url, optional_modules, @@ -188,6 +189,7 @@ class Installer: # run through the configuration flow self.instance.configure() + class InvokeAiInstance: """ Manages an installed instance of InvokeAI, comprising a virtual environment and a runtime directory. @@ -196,7 +198,6 @@ class InvokeAiInstance: """ def __init__(self, runtime: Path, venv: Path, version: str) -> None: - self.runtime = runtime self.venv = venv self.pip = get_pip_from_venv(venv) @@ -312,7 +313,7 @@ class InvokeAiInstance: "install", "--require-virtualenv", "--use-pep517", - str(src)+(optional_modules if optional_modules else ''), + str(src) + (optional_modules if optional_modules else ""), "--find-links" if find_links is not None else None, find_links, "--extra-index-url" if extra_index_url is not None else None, @@ -329,15 +330,15 @@ class InvokeAiInstance: # set sys.argv to a consistent state new_argv = [sys.argv[0]] - for i in range(1,len(sys.argv)): + for i in range(1, len(sys.argv)): el = sys.argv[i] - if el in ['-r','--root']: + if el in ["-r", "--root"]: new_argv.append(el) - new_argv.append(sys.argv[i+1]) - elif el in ['-y','--yes','--yes-to-all']: + new_argv.append(sys.argv[i + 1]) + elif el in ["-y", "--yes", "--yes-to-all"]: new_argv.append(el) sys.argv = new_argv - + import requests # to catch download exceptions from messages import introduction @@ -353,16 +354,16 @@ class InvokeAiInstance: invokeai_configure() succeeded = True except requests.exceptions.ConnectionError as e: - print(f'\nA network error was encountered during configuration and download: {str(e)}') + print(f"\nA network error was encountered during configuration and download: {str(e)}") except OSError as e: - print(f'\nAn OS error was encountered during configuration and download: {str(e)}') + print(f"\nAn OS error was encountered during configuration and download: {str(e)}") except Exception as e: - print(f'\nA problem was encountered during the configuration and download steps: {str(e)}') + print(f"\nA problem was encountered during the configuration and download steps: {str(e)}") finally: if not succeeded: print('To try again, find the "invokeai" directory, run the script "invoke.sh" or "invoke.bat"') - print('and choose option 7 to fix a broken install, optionally followed by option 5 to install models.') - print('Alternatively you can relaunch the installer.') + print("and choose option 7 to fix a broken install, optionally followed by option 5 to install models.") + print("Alternatively you can relaunch the installer.") def install_user_scripts(self): """ @@ -371,11 +372,11 @@ class InvokeAiInstance: ext = "bat" if OS == "Windows" else "sh" - #scripts = ['invoke', 'update'] - scripts = ['invoke'] - + # scripts = ['invoke', 'update'] + scripts = ["invoke"] + for script in scripts: - src = Path(__file__).parent / '..' / "templates" / f"{script}.{ext}.in" + src = Path(__file__).parent / ".." / "templates" / f"{script}.{ext}.in" dest = self.runtime / f"{script}.{ext}" shutil.copy(src, dest) os.chmod(dest, 0o0755) @@ -420,11 +421,7 @@ def set_sys_path(venv_path: Path) -> None: # filter out any paths in sys.path that may be system- or user-wide # but leave the temporary bootstrap virtualenv as it contains packages we # temporarily need at install time - sys.path = list(filter( - lambda p: not p.endswith("-packages") - or p.find(BOOTSTRAP_VENV_PREFIX) != -1, - sys.path - )) + sys.path = list(filter(lambda p: not p.endswith("-packages") or p.find(BOOTSTRAP_VENV_PREFIX) != -1, sys.path)) # determine site-packages/lib directory location for the venv lib = "Lib" if OS == "Windows" else f"lib/python{sys.version_info.major}.{sys.version_info.minor}" @@ -433,7 +430,7 @@ def set_sys_path(venv_path: Path) -> None: sys.path.append(str(Path(venv_path, lib, "site-packages").expanduser().resolve())) -def get_torch_source() -> (Union[str, None],str): +def get_torch_source() -> (Union[str, None], str): """ Determine the extra index URL for pip to use for torch installation. This depends on the OS and the graphics accelerator in use. @@ -461,9 +458,9 @@ def get_torch_source() -> (Union[str, None],str): elif device == "cpu": url = "https://download.pytorch.org/whl/cpu" - if device == 'cuda': - url = 'https://download.pytorch.org/whl/cu117' - optional_modules = '[xformers]' + if device == "cuda": + url = "https://download.pytorch.org/whl/cu117" + optional_modules = "[xformers]" # in all other cases, Torch wheels should be coming from PyPi as of Torch 1.13 diff --git a/installer/lib/main.py b/installer/lib/main.py index 42460bb0e8..b442f49255 100644 --- a/installer/lib/main.py +++ b/installer/lib/main.py @@ -41,7 +41,7 @@ if __name__ == "__main__": type=Path, default=None, ) - + args = parser.parse_args() inst = Installer() diff --git a/installer/lib/messages.py b/installer/lib/messages.py index 196c0e1eb0..3687b52d32 100644 --- a/installer/lib/messages.py +++ b/installer/lib/messages.py @@ -36,13 +36,15 @@ else: def welcome(): - @group() def text(): if (platform_specific := _platform_specific_help()) != "": yield platform_specific yield "" - yield Text.from_markup("Some of the installation steps take a long time to run. Please be patient. If the script appears to hang for more than 10 minutes, please interrupt with [i]Control-C[/] and retry.", justify="center") + yield Text.from_markup( + "Some of the installation steps take a long time to run. Please be patient. If the script appears to hang for more than 10 minutes, please interrupt with [i]Control-C[/] and retry.", + justify="center", + ) console.rule() print( @@ -58,6 +60,7 @@ def welcome(): ) console.line() + def confirm_install(dest: Path) -> bool: if dest.exists(): print(f":exclamation: Directory {dest} already exists :exclamation:") @@ -92,7 +95,6 @@ def dest_path(dest=None) -> Path: dest_confirmed = confirm_install(dest) while not dest_confirmed: - # if the given destination already exists, the starting point for browsing is its parent directory. # the user may have made a typo, or otherwise wants to place the root dir next to an existing one. # if the destination dir does NOT exist, then the user must have changed their mind about the selection. @@ -300,15 +302,20 @@ def introduction() -> None: ) console.line(2) -def _platform_specific_help()->str: + +def _platform_specific_help() -> str: if OS == "Darwin": - text = Text.from_markup("""[b wheat1]macOS Users![/]\n\nPlease be sure you have the [b wheat1]Xcode command-line tools[/] installed before continuing.\nIf not, cancel with [i]Control-C[/] and follow the Xcode install instructions at [deep_sky_blue1]https://www.freecodecamp.org/news/install-xcode-command-line-tools/[/].""") + text = Text.from_markup( + """[b wheat1]macOS Users![/]\n\nPlease be sure you have the [b wheat1]Xcode command-line tools[/] installed before continuing.\nIf not, cancel with [i]Control-C[/] and follow the Xcode install instructions at [deep_sky_blue1]https://www.freecodecamp.org/news/install-xcode-command-line-tools/[/].""" + ) elif OS == "Windows": - text = Text.from_markup("""[b wheat1]Windows Users![/]\n\nBefore you start, please do the following: + text = Text.from_markup( + """[b wheat1]Windows Users![/]\n\nBefore you start, please do the following: 1. Double-click on the file [b wheat1]WinLongPathsEnabled.reg[/] in order to enable long path support on your system. 2. Make sure you have the [b wheat1]Visual C++ core libraries[/] installed. If not, install from - [deep_sky_blue1]https://learn.microsoft.com/en-US/cpp/windows/latest-supported-vc-redist?view=msvc-170[/]""") + [deep_sky_blue1]https://learn.microsoft.com/en-US/cpp/windows/latest-supported-vc-redist?view=msvc-170[/]""" + ) else: text = "" return text diff --git a/invokeai/app/api/dependencies.py b/invokeai/app/api/dependencies.py index 050d1b091f..a186daedf5 100644 --- a/invokeai/app/api/dependencies.py +++ b/invokeai/app/api/dependencies.py @@ -78,9 +78,7 @@ class ApiDependencies: image_record_storage = SqliteImageRecordStorage(db_location) image_file_storage = DiskImageFileStorage(f"{output_folder}/images") names = SimpleNameService() - latents = ForwardCacheLatentsStorage( - DiskLatentsStorage(f"{output_folder}/latents") - ) + latents = ForwardCacheLatentsStorage(DiskLatentsStorage(f"{output_folder}/latents")) board_record_storage = SqliteBoardRecordStorage(db_location) board_image_record_storage = SqliteBoardImageRecordStorage(db_location) @@ -125,9 +123,7 @@ class ApiDependencies: boards=boards, board_images=board_images, queue=MemoryInvocationQueue(), - graph_library=SqliteItemStorage[LibraryGraph]( - filename=db_location, table_name="graphs" - ), + graph_library=SqliteItemStorage[LibraryGraph](filename=db_location, table_name="graphs"), graph_execution_manager=graph_execution_manager, processor=DefaultInvocationProcessor(), configuration=config, diff --git a/invokeai/app/api/routers/app_info.py b/invokeai/app/api/routers/app_info.py index e37184a77b..9d9e47d2ef 100644 --- a/invokeai/app/api/routers/app_info.py +++ b/invokeai/app/api/routers/app_info.py @@ -15,6 +15,7 @@ from invokeai.version import __version__ from ..dependencies import ApiDependencies from invokeai.backend.util.logging import logging + class LogLevel(int, Enum): NotSet = logging.NOTSET Debug = logging.DEBUG @@ -23,10 +24,12 @@ class LogLevel(int, Enum): Error = logging.ERROR Critical = logging.CRITICAL + class Upscaler(BaseModel): upscaling_method: str = Field(description="Name of upscaling method") upscaling_models: list[str] = Field(description="List of upscaling models for this method") - + + app_router = APIRouter(prefix="/v1/app", tags=["app"]) @@ -45,38 +48,30 @@ class AppConfig(BaseModel): watermarking_methods: list[str] = Field(description="List of invisible watermark methods") -@app_router.get( - "/version", operation_id="app_version", status_code=200, response_model=AppVersion -) +@app_router.get("/version", operation_id="app_version", status_code=200, response_model=AppVersion) async def get_version() -> AppVersion: return AppVersion(version=__version__) -@app_router.get( - "/config", operation_id="get_config", status_code=200, response_model=AppConfig -) +@app_router.get("/config", operation_id="get_config", status_code=200, response_model=AppConfig) async def get_config() -> AppConfig: - infill_methods = ['tile'] + infill_methods = ["tile"] if PatchMatch.patchmatch_available(): - infill_methods.append('patchmatch') - + infill_methods.append("patchmatch") upscaling_models = [] for model in typing.get_args(ESRGAN_MODELS): upscaling_models.append(str(Path(model).stem)) - upscaler = Upscaler( - upscaling_method = 'esrgan', - upscaling_models = upscaling_models - ) - + upscaler = Upscaler(upscaling_method="esrgan", upscaling_models=upscaling_models) + nsfw_methods = [] if SafetyChecker.safety_checker_available(): - nsfw_methods.append('nsfw_checker') + nsfw_methods.append("nsfw_checker") watermarking_methods = [] if InvisibleWatermark.invisible_watermark_available(): - watermarking_methods.append('invisible_watermark') - + watermarking_methods.append("invisible_watermark") + return AppConfig( infill_methods=infill_methods, upscaling_methods=[upscaler], @@ -84,25 +79,26 @@ async def get_config() -> AppConfig: watermarking_methods=watermarking_methods, ) + @app_router.get( "/logging", operation_id="get_log_level", - responses={200: {"description" : "The operation was successful"}}, - response_model = LogLevel, + responses={200: {"description": "The operation was successful"}}, + response_model=LogLevel, ) -async def get_log_level( -) -> LogLevel: +async def get_log_level() -> LogLevel: """Returns the log level""" return LogLevel(ApiDependencies.invoker.services.logger.level) + @app_router.post( "/logging", operation_id="set_log_level", - responses={200: {"description" : "The operation was successful"}}, - response_model = LogLevel, + responses={200: {"description": "The operation was successful"}}, + response_model=LogLevel, ) async def set_log_level( - level: LogLevel = Body(description="New log verbosity level"), + level: LogLevel = Body(description="New log verbosity level"), ) -> LogLevel: """Sets the log verbosity level""" ApiDependencies.invoker.services.logger.setLevel(level) diff --git a/invokeai/app/api/routers/board_images.py b/invokeai/app/api/routers/board_images.py index 651310af24..6cb073ca7c 100644 --- a/invokeai/app/api/routers/board_images.py +++ b/invokeai/app/api/routers/board_images.py @@ -52,4 +52,3 @@ async def remove_board_image( return result except Exception as e: raise HTTPException(status_code=500, detail="Failed to update board") - diff --git a/invokeai/app/api/routers/boards.py b/invokeai/app/api/routers/boards.py index f3de7f4952..69f4a8b3a7 100644 --- a/invokeai/app/api/routers/boards.py +++ b/invokeai/app/api/routers/boards.py @@ -18,9 +18,7 @@ class DeleteBoardResult(BaseModel): deleted_board_images: list[str] = Field( description="The image names of the board-images relationships that were deleted." ) - deleted_images: list[str] = Field( - description="The names of the images that were deleted." - ) + deleted_images: list[str] = Field(description="The names of the images that were deleted.") @boards_router.post( @@ -73,22 +71,16 @@ async def update_board( ) -> BoardDTO: """Updates a board""" try: - result = ApiDependencies.invoker.services.boards.update( - board_id=board_id, changes=changes - ) + result = ApiDependencies.invoker.services.boards.update(board_id=board_id, changes=changes) return result except Exception as e: raise HTTPException(status_code=500, detail="Failed to update board") -@boards_router.delete( - "/{board_id}", operation_id="delete_board", response_model=DeleteBoardResult -) +@boards_router.delete("/{board_id}", operation_id="delete_board", response_model=DeleteBoardResult) async def delete_board( board_id: str = Path(description="The id of board to delete"), - include_images: Optional[bool] = Query( - description="Permanently delete all images on the board", default=False - ), + include_images: Optional[bool] = Query(description="Permanently delete all images on the board", default=False), ) -> DeleteBoardResult: """Deletes a board""" try: @@ -96,9 +88,7 @@ async def delete_board( deleted_images = ApiDependencies.invoker.services.board_images.get_all_board_image_names_for_board( board_id=board_id ) - ApiDependencies.invoker.services.images.delete_images_on_board( - board_id=board_id - ) + ApiDependencies.invoker.services.images.delete_images_on_board(board_id=board_id) ApiDependencies.invoker.services.boards.delete(board_id=board_id) return DeleteBoardResult( board_id=board_id, @@ -127,9 +117,7 @@ async def delete_board( async def list_boards( all: Optional[bool] = Query(default=None, description="Whether to list all boards"), offset: Optional[int] = Query(default=None, description="The page offset"), - limit: Optional[int] = Query( - default=None, description="The number of boards per page" - ), + limit: Optional[int] = Query(default=None, description="The number of boards per page"), ) -> Union[OffsetPaginatedResults[BoardDTO], list[BoardDTO]]: """Gets a list of boards""" if all: diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.py index 36e2e3d75d..498a1139e4 100644 --- a/invokeai/app/api/routers/images.py +++ b/invokeai/app/api/routers/images.py @@ -40,15 +40,9 @@ async def upload_image( response: Response, image_category: ImageCategory = Query(description="The category of the image"), is_intermediate: bool = Query(description="Whether this is an intermediate image"), - board_id: Optional[str] = Query( - default=None, description="The board to add this image to, if any" - ), - session_id: Optional[str] = Query( - default=None, description="The session ID associated with this upload, if any" - ), - crop_visible: Optional[bool] = Query( - default=False, description="Whether to crop the image" - ), + board_id: Optional[str] = Query(default=None, description="The board to add this image to, if any"), + session_id: Optional[str] = Query(default=None, description="The session ID associated with this upload, if any"), + crop_visible: Optional[bool] = Query(default=False, description="Whether to crop the image"), ) -> ImageDTO: """Uploads an image""" if not file.content_type.startswith("image"): @@ -115,9 +109,7 @@ async def clear_intermediates() -> int: ) async def update_image( image_name: str = Path(description="The name of the image to update"), - image_changes: ImageRecordChanges = Body( - description="The changes to apply to the image" - ), + image_changes: ImageRecordChanges = Body(description="The changes to apply to the image"), ) -> ImageDTO: """Updates an image""" @@ -212,15 +204,11 @@ async def get_image_thumbnail( """Gets a thumbnail image file""" try: - path = ApiDependencies.invoker.services.images.get_path( - image_name, thumbnail=True - ) + path = ApiDependencies.invoker.services.images.get_path(image_name, thumbnail=True) if not ApiDependencies.invoker.services.images.validate_path(path): raise HTTPException(status_code=404) - response = FileResponse( - path, media_type="image/webp", content_disposition_type="inline" - ) + response = FileResponse(path, media_type="image/webp", content_disposition_type="inline") response.headers["Cache-Control"] = f"max-age={IMAGE_MAX_AGE}" return response except Exception as e: @@ -239,9 +227,7 @@ async def get_image_urls( try: image_url = ApiDependencies.invoker.services.images.get_url(image_name) - thumbnail_url = ApiDependencies.invoker.services.images.get_url( - image_name, thumbnail=True - ) + thumbnail_url = ApiDependencies.invoker.services.images.get_url(image_name, thumbnail=True) return ImageUrlsDTO( image_name=image_name, image_url=image_url, @@ -257,15 +243,9 @@ async def get_image_urls( response_model=OffsetPaginatedResults[ImageDTO], ) async def list_image_dtos( - image_origin: Optional[ResourceOrigin] = Query( - default=None, description="The origin of images to list." - ), - categories: Optional[list[ImageCategory]] = Query( - default=None, description="The categories of image to include." - ), - is_intermediate: Optional[bool] = Query( - default=None, description="Whether to list intermediate images." - ), + image_origin: Optional[ResourceOrigin] = Query(default=None, description="The origin of images to list."), + categories: Optional[list[ImageCategory]] = Query(default=None, description="The categories of image to include."), + is_intermediate: Optional[bool] = Query(default=None, description="Whether to list intermediate images."), board_id: Optional[str] = Query( default=None, description="The board id to filter by. Use 'none' to find images without a board.", diff --git a/invokeai/app/api/routers/models.py b/invokeai/app/api/routers/models.py index 759f6c9f59..2f59f1dd0f 100644 --- a/invokeai/app/api/routers/models.py +++ b/invokeai/app/api/routers/models.py @@ -28,49 +28,52 @@ ConvertModelResponse = Union[tuple(OPENAPI_MODEL_CONFIGS)] MergeModelResponse = Union[tuple(OPENAPI_MODEL_CONFIGS)] ImportModelAttributes = Union[tuple(OPENAPI_MODEL_CONFIGS)] + class ModelsList(BaseModel): models: list[Union[tuple(OPENAPI_MODEL_CONFIGS)]] + @models_router.get( "/", operation_id="list_models", - responses={200: {"model": ModelsList }}, + responses={200: {"model": ModelsList}}, ) async def list_models( base_models: Optional[List[BaseModelType]] = Query(default=None, description="Base models to include"), model_type: Optional[ModelType] = Query(default=None, description="The type of model to get"), ) -> ModelsList: """Gets a list of models""" - if base_models and len(base_models)>0: + if base_models and len(base_models) > 0: models_raw = list() for base_model in base_models: models_raw.extend(ApiDependencies.invoker.services.model_manager.list_models(base_model, model_type)) else: models_raw = ApiDependencies.invoker.services.model_manager.list_models(None, model_type) - models = parse_obj_as(ModelsList, { "models": models_raw }) + models = parse_obj_as(ModelsList, {"models": models_raw}) return models + @models_router.patch( "/{base_model}/{model_type}/{model_name}", operation_id="update_model", - responses={200: {"description" : "The model was updated successfully"}, - 400: {"description" : "Bad request"}, - 404: {"description" : "The model could not be found"}, - 409: {"description" : "There is already a model corresponding to the new name"}, - }, - status_code = 200, - response_model = UpdateModelResponse, + responses={ + 200: {"description": "The model was updated successfully"}, + 400: {"description": "Bad request"}, + 404: {"description": "The model could not be found"}, + 409: {"description": "There is already a model corresponding to the new name"}, + }, + status_code=200, + response_model=UpdateModelResponse, ) async def update_model( - base_model: BaseModelType = Path(description="Base model"), - model_type: ModelType = Path(description="The type of model"), - model_name: str = Path(description="model name"), - info: Union[tuple(OPENAPI_MODEL_CONFIGS)] = Body(description="Model configuration"), + base_model: BaseModelType = Path(description="Base model"), + model_type: ModelType = Path(description="The type of model"), + model_name: str = Path(description="model name"), + info: Union[tuple(OPENAPI_MODEL_CONFIGS)] = Body(description="Model configuration"), ) -> UpdateModelResponse: - """ Update model contents with a new config. If the model name or base fields are changed, then the model is renamed. """ + """Update model contents with a new config. If the model name or base fields are changed, then the model is renamed.""" logger = ApiDependencies.invoker.services.logger - try: previous_info = ApiDependencies.invoker.services.model_manager.list_model( model_name=model_name, @@ -81,13 +84,13 @@ async def update_model( # rename operation requested if info.model_name != model_name or info.base_model != base_model: ApiDependencies.invoker.services.model_manager.rename_model( - base_model = base_model, - model_type = model_type, - model_name = model_name, - new_name = info.model_name, - new_base = info.base_model, + base_model=base_model, + model_type=model_type, + model_name=model_name, + new_name=info.model_name, + new_base=info.base_model, ) - logger.info(f'Successfully renamed {base_model}/{model_name}=>{info.base_model}/{info.model_name}') + logger.info(f"Successfully renamed {base_model.value}/{model_name}=>{info.base_model}/{info.model_name}") # update information to support an update of attributes model_name = info.model_name base_model = info.base_model @@ -96,16 +99,15 @@ async def update_model( base_model=base_model, model_type=model_type, ) - if new_info.get('path') != previous_info.get('path'): # model manager moved model path during rename - don't overwrite it - info.path = new_info.get('path') - + if new_info.get("path") != previous_info.get( + "path" + ): # model manager moved model path during rename - don't overwrite it + info.path = new_info.get("path") + ApiDependencies.invoker.services.model_manager.update_model( - model_name=model_name, - base_model=base_model, - model_type=model_type, - model_attributes=info.dict() + model_name=model_name, base_model=base_model, model_type=model_type, model_attributes=info.dict() ) - + model_raw = ApiDependencies.invoker.services.model_manager.list_model( model_name=model_name, base_model=base_model, @@ -123,49 +125,48 @@ async def update_model( return model_response + @models_router.post( "/import", operation_id="import_model", - responses= { - 201: {"description" : "The model imported successfully"}, - 404: {"description" : "The model could not be found"}, - 415: {"description" : "Unrecognized file/folder format"}, - 424: {"description" : "The model appeared to import successfully, but could not be found in the model manager"}, - 409: {"description" : "There is already a model corresponding to this path or repo_id"}, + responses={ + 201: {"description": "The model imported successfully"}, + 404: {"description": "The model could not be found"}, + 415: {"description": "Unrecognized file/folder format"}, + 424: {"description": "The model appeared to import successfully, but could not be found in the model manager"}, + 409: {"description": "There is already a model corresponding to this path or repo_id"}, }, status_code=201, - response_model=ImportModelResponse + response_model=ImportModelResponse, ) async def import_model( - location: str = Body(description="A model path, repo_id or URL to import"), - prediction_type: Optional[Literal['v_prediction','epsilon','sample']] = \ - Body(description='Prediction type for SDv2 checkpoint files', default="v_prediction"), + location: str = Body(description="A model path, repo_id or URL to import"), + prediction_type: Optional[Literal["v_prediction", "epsilon", "sample"]] = Body( + description="Prediction type for SDv2 checkpoint files", default="v_prediction" + ), ) -> ImportModelResponse: - """ Add a model using its local path, repo_id, or remote URL. Model characteristics will be probed and configured automatically """ - + """Add a model using its local path, repo_id, or remote URL. Model characteristics will be probed and configured automatically""" + items_to_import = {location} - prediction_types = { x.value: x for x in SchedulerPredictionType } + prediction_types = {x.value: x for x in SchedulerPredictionType} logger = ApiDependencies.invoker.services.logger try: installed_models = ApiDependencies.invoker.services.model_manager.heuristic_import( - items_to_import = items_to_import, - prediction_type_helper = lambda x: prediction_types.get(prediction_type) + items_to_import=items_to_import, prediction_type_helper=lambda x: prediction_types.get(prediction_type) ) info = installed_models.get(location) if not info: logger.error("Import failed") raise HTTPException(status_code=415) - - logger.info(f'Successfully imported {location}, got {info}') + + logger.info(f"Successfully imported {location}, got {info}") model_raw = ApiDependencies.invoker.services.model_manager.list_model( - model_name=info.name, - base_model=info.base_model, - model_type=info.model_type + model_name=info.name, base_model=info.base_model, model_type=info.model_type ) return parse_obj_as(ImportModelResponse, model_raw) - + except ModelNotFoundException as e: logger.error(str(e)) raise HTTPException(status_code=404, detail=str(e)) @@ -175,38 +176,34 @@ async def import_model( except ValueError as e: logger.error(str(e)) raise HTTPException(status_code=409, detail=str(e)) - + + @models_router.post( "/add", operation_id="add_model", - responses= { - 201: {"description" : "The model added successfully"}, - 404: {"description" : "The model could not be found"}, - 424: {"description" : "The model appeared to add successfully, but could not be found in the model manager"}, - 409: {"description" : "There is already a model corresponding to this path or repo_id"}, + responses={ + 201: {"description": "The model added successfully"}, + 404: {"description": "The model could not be found"}, + 424: {"description": "The model appeared to add successfully, but could not be found in the model manager"}, + 409: {"description": "There is already a model corresponding to this path or repo_id"}, }, status_code=201, - response_model=ImportModelResponse + response_model=ImportModelResponse, ) async def add_model( - info: Union[tuple(OPENAPI_MODEL_CONFIGS)] = Body(description="Model configuration"), + info: Union[tuple(OPENAPI_MODEL_CONFIGS)] = Body(description="Model configuration"), ) -> ImportModelResponse: - """ Add a model using the configuration information appropriate for its type. Only local models can be added by path""" - + """Add a model using the configuration information appropriate for its type. Only local models can be added by path""" + logger = ApiDependencies.invoker.services.logger try: ApiDependencies.invoker.services.model_manager.add_model( - info.model_name, - info.base_model, - info.model_type, - model_attributes = info.dict() + info.model_name, info.base_model, info.model_type, model_attributes=info.dict() ) - logger.info(f'Successfully added {info.model_name}') + logger.info(f"Successfully added {info.model_name}") model_raw = ApiDependencies.invoker.services.model_manager.list_model( - model_name=info.model_name, - base_model=info.base_model, - model_type=info.model_type + model_name=info.model_name, base_model=info.base_model, model_type=info.model_type ) return parse_obj_as(ImportModelResponse, model_raw) except ModelNotFoundException as e: @@ -216,66 +213,66 @@ async def add_model( logger.error(str(e)) raise HTTPException(status_code=409, detail=str(e)) - + @models_router.delete( "/{base_model}/{model_type}/{model_name}", operation_id="del_model", - responses={ - 204: { "description": "Model deleted successfully" }, - 404: { "description": "Model not found" } - }, - status_code = 204, - response_model = None, + responses={204: {"description": "Model deleted successfully"}, 404: {"description": "Model not found"}}, + status_code=204, + response_model=None, ) async def delete_model( - base_model: BaseModelType = Path(description="Base model"), - model_type: ModelType = Path(description="The type of model"), - model_name: str = Path(description="model name"), + base_model: BaseModelType = Path(description="Base model"), + model_type: ModelType = Path(description="The type of model"), + model_name: str = Path(description="model name"), ) -> Response: """Delete Model""" logger = ApiDependencies.invoker.services.logger - + try: - ApiDependencies.invoker.services.model_manager.del_model(model_name, - base_model = base_model, - model_type = model_type - ) + ApiDependencies.invoker.services.model_manager.del_model( + model_name, base_model=base_model, model_type=model_type + ) logger.info(f"Deleted model: {model_name}") return Response(status_code=204) except ModelNotFoundException as e: logger.error(str(e)) raise HTTPException(status_code=404, detail=str(e)) + @models_router.put( "/convert/{base_model}/{model_type}/{model_name}", operation_id="convert_model", responses={ - 200: { "description": "Model converted successfully" }, - 400: {"description" : "Bad request" }, - 404: { "description": "Model not found" }, + 200: {"description": "Model converted successfully"}, + 400: {"description": "Bad request"}, + 404: {"description": "Model not found"}, }, - status_code = 200, - response_model = ConvertModelResponse, + status_code=200, + response_model=ConvertModelResponse, ) async def convert_model( - base_model: BaseModelType = Path(description="Base model"), - model_type: ModelType = Path(description="The type of model"), - model_name: str = Path(description="model name"), - convert_dest_directory: Optional[str] = Query(default=None, description="Save the converted model to the designated directory"), + base_model: BaseModelType = Path(description="Base model"), + model_type: ModelType = Path(description="The type of model"), + model_name: str = Path(description="model name"), + convert_dest_directory: Optional[str] = Query( + default=None, description="Save the converted model to the designated directory" + ), ) -> ConvertModelResponse: """Convert a checkpoint model into a diffusers model, optionally saving to the indicated destination directory, or `models` if none.""" logger = ApiDependencies.invoker.services.logger try: logger.info(f"Converting model: {model_name}") dest = pathlib.Path(convert_dest_directory) if convert_dest_directory else None - ApiDependencies.invoker.services.model_manager.convert_model(model_name, - base_model = base_model, - model_type = model_type, - convert_dest_directory = dest, - ) - model_raw = ApiDependencies.invoker.services.model_manager.list_model(model_name, - base_model = base_model, - model_type = model_type) + ApiDependencies.invoker.services.model_manager.convert_model( + model_name, + base_model=base_model, + model_type=model_type, + convert_dest_directory=dest, + ) + model_raw = ApiDependencies.invoker.services.model_manager.list_model( + model_name, base_model=base_model, model_type=model_type + ) response = parse_obj_as(ConvertModelResponse, model_raw) except ModelNotFoundException as e: raise HTTPException(status_code=404, detail=f"Model '{model_name}' not found: {str(e)}") @@ -283,91 +280,101 @@ async def convert_model( raise HTTPException(status_code=400, detail=str(e)) return response + @models_router.get( "/search", operation_id="search_for_models", responses={ - 200: { "description": "Directory searched successfully" }, - 404: { "description": "Invalid directory path" }, + 200: {"description": "Directory searched successfully"}, + 404: {"description": "Invalid directory path"}, }, - status_code = 200, - response_model = List[pathlib.Path] + status_code=200, + response_model=List[pathlib.Path], ) async def search_for_models( - search_path: pathlib.Path = Query(description="Directory path to search for models") -)->List[pathlib.Path]: + search_path: pathlib.Path = Query(description="Directory path to search for models"), +) -> List[pathlib.Path]: if not search_path.is_dir(): - raise HTTPException(status_code=404, detail=f"The search path '{search_path}' does not exist or is not directory") + raise HTTPException( + status_code=404, detail=f"The search path '{search_path}' does not exist or is not directory" + ) return ApiDependencies.invoker.services.model_manager.search_for_models(search_path) + @models_router.get( "/ckpt_confs", operation_id="list_ckpt_configs", responses={ - 200: { "description" : "paths retrieved successfully" }, + 200: {"description": "paths retrieved successfully"}, }, - status_code = 200, - response_model = List[pathlib.Path] + status_code=200, + response_model=List[pathlib.Path], ) -async def list_ckpt_configs( -)->List[pathlib.Path]: +async def list_ckpt_configs() -> List[pathlib.Path]: """Return a list of the legacy checkpoint configuration files stored in `ROOT/configs/stable-diffusion`, relative to ROOT.""" return ApiDependencies.invoker.services.model_manager.list_checkpoint_configs() - - + + @models_router.post( "/sync", operation_id="sync_to_config", responses={ - 201: { "description": "synchronization successful" }, + 201: {"description": "synchronization successful"}, }, - status_code = 201, - response_model = bool + status_code=201, + response_model=bool, ) -async def sync_to_config( -)->bool: +async def sync_to_config() -> bool: """Call after making changes to models.yaml, autoimport directories or models directory to synchronize in-memory data structures with disk data structures.""" ApiDependencies.invoker.services.model_manager.sync_to_config() return True - + + @models_router.put( "/merge/{base_model}", operation_id="merge_models", responses={ - 200: { "description": "Model converted successfully" }, - 400: { "description": "Incompatible models" }, - 404: { "description": "One or more models not found" }, + 200: {"description": "Model converted successfully"}, + 400: {"description": "Incompatible models"}, + 404: {"description": "One or more models not found"}, }, - status_code = 200, - response_model = MergeModelResponse, + status_code=200, + response_model=MergeModelResponse, ) async def merge_models( - base_model: BaseModelType = Path(description="Base model"), - model_names: List[str] = Body(description="model name", min_items=2, max_items=3), - merged_model_name: Optional[str] = Body(description="Name of destination model"), - alpha: Optional[float] = Body(description="Alpha weighting strength to apply to 2d and 3d models", default=0.5), - interp: Optional[MergeInterpolationMethod] = Body(description="Interpolation method"), - force: Optional[bool] = Body(description="Force merging of models created with different versions of diffusers", default=False), - merge_dest_directory: Optional[str] = Body(description="Save the merged model to the designated directory (with 'merged_model_name' appended)", default=None) + base_model: BaseModelType = Path(description="Base model"), + model_names: List[str] = Body(description="model name", min_items=2, max_items=3), + merged_model_name: Optional[str] = Body(description="Name of destination model"), + alpha: Optional[float] = Body(description="Alpha weighting strength to apply to 2d and 3d models", default=0.5), + interp: Optional[MergeInterpolationMethod] = Body(description="Interpolation method"), + force: Optional[bool] = Body( + description="Force merging of models created with different versions of diffusers", default=False + ), + merge_dest_directory: Optional[str] = Body( + description="Save the merged model to the designated directory (with 'merged_model_name' appended)", + default=None, + ), ) -> MergeModelResponse: """Convert a checkpoint model into a diffusers model""" logger = ApiDependencies.invoker.services.logger try: logger.info(f"Merging models: {model_names} into {merge_dest_directory or ''}/{merged_model_name}") dest = pathlib.Path(merge_dest_directory) if merge_dest_directory else None - result = ApiDependencies.invoker.services.model_manager.merge_models(model_names, - base_model, - merged_model_name=merged_model_name or "+".join(model_names), - alpha=alpha, - interp=interp, - force=force, - merge_dest_directory = dest - ) - model_raw = ApiDependencies.invoker.services.model_manager.list_model(result.name, - base_model = base_model, - model_type = ModelType.Main, - ) + result = ApiDependencies.invoker.services.model_manager.merge_models( + model_names, + base_model, + merged_model_name=merged_model_name or "+".join(model_names), + alpha=alpha, + interp=interp, + force=force, + merge_dest_directory=dest, + ) + model_raw = ApiDependencies.invoker.services.model_manager.list_model( + result.name, + base_model=base_model, + model_type=ModelType.Main, + ) response = parse_obj_as(ConvertModelResponse, model_raw) except ModelNotFoundException: raise HTTPException(status_code=404, detail=f"One or more of the models '{model_names}' not found") diff --git a/invokeai/app/api/routers/sessions.py b/invokeai/app/api/routers/sessions.py index da842a3968..e4ba2a353e 100644 --- a/invokeai/app/api/routers/sessions.py +++ b/invokeai/app/api/routers/sessions.py @@ -30,9 +30,7 @@ session_router = APIRouter(prefix="/v1/sessions", tags=["sessions"]) }, ) async def create_session( - graph: Optional[Graph] = Body( - default=None, description="The graph to initialize the session with" - ) + graph: Optional[Graph] = Body(default=None, description="The graph to initialize the session with") ) -> GraphExecutionState: """Creates a new session, optionally initializing it with an invocation graph""" session = ApiDependencies.invoker.create_execution_state(graph) @@ -51,13 +49,9 @@ async def list_sessions( ) -> PaginatedResults[GraphExecutionState]: """Gets a list of sessions, optionally searching""" if query == "": - result = ApiDependencies.invoker.services.graph_execution_manager.list( - page, per_page - ) + result = ApiDependencies.invoker.services.graph_execution_manager.list(page, per_page) else: - result = ApiDependencies.invoker.services.graph_execution_manager.search( - query, page, per_page - ) + result = ApiDependencies.invoker.services.graph_execution_manager.search(query, page, per_page) return result @@ -91,9 +85,9 @@ async def get_session( ) async def add_node( session_id: str = Path(description="The id of the session"), - node: Annotated[ - Union[BaseInvocation.get_invocations()], Field(discriminator="type") # type: ignore - ] = Body(description="The node to add"), + node: Annotated[Union[BaseInvocation.get_invocations()], Field(discriminator="type")] = Body( # type: ignore + description="The node to add" + ), ) -> str: """Adds a node to the graph""" session = ApiDependencies.invoker.services.graph_execution_manager.get(session_id) @@ -124,9 +118,9 @@ async def add_node( async def update_node( session_id: str = Path(description="The id of the session"), node_path: str = Path(description="The path to the node in the graph"), - node: Annotated[ - Union[BaseInvocation.get_invocations()], Field(discriminator="type") # type: ignore - ] = Body(description="The new node"), + node: Annotated[Union[BaseInvocation.get_invocations()], Field(discriminator="type")] = Body( # type: ignore + description="The new node" + ), ) -> GraphExecutionState: """Updates a node in the graph and removes all linked edges""" session = ApiDependencies.invoker.services.graph_execution_manager.get(session_id) @@ -230,7 +224,7 @@ async def delete_edge( try: edge = Edge( source=EdgeConnection(node_id=from_node_id, field=from_field), - destination=EdgeConnection(node_id=to_node_id, field=to_field) + destination=EdgeConnection(node_id=to_node_id, field=to_field), ) session.delete_edge(edge) ApiDependencies.invoker.services.graph_execution_manager.set( @@ -255,9 +249,7 @@ async def delete_edge( ) async def invoke_session( session_id: str = Path(description="The id of the session to invoke"), - all: bool = Query( - default=False, description="Whether or not to invoke all remaining invocations" - ), + all: bool = Query(default=False, description="Whether or not to invoke all remaining invocations"), ) -> Response: """Invokes a session""" session = ApiDependencies.invoker.services.graph_execution_manager.get(session_id) @@ -274,9 +266,7 @@ async def invoke_session( @session_router.delete( "/{session_id}/invoke", operation_id="cancel_session_invoke", - responses={ - 202: {"description": "The invocation is canceled"} - }, + responses={202: {"description": "The invocation is canceled"}}, ) async def cancel_session_invoke( session_id: str = Path(description="The id of the session to cancel"), diff --git a/invokeai/app/api/sockets.py b/invokeai/app/api/sockets.py index f70d7a6609..4591bac540 100644 --- a/invokeai/app/api/sockets.py +++ b/invokeai/app/api/sockets.py @@ -16,9 +16,7 @@ class SocketIO: self.__sio.on("subscribe", handler=self._handle_sub) self.__sio.on("unsubscribe", handler=self._handle_unsub) - local_handler.register( - event_name=EventServiceBase.session_event, _func=self._handle_session_event - ) + local_handler.register(event_name=EventServiceBase.session_event, _func=self._handle_session_event) async def _handle_session_event(self, event: Event): await self.__sio.emit( diff --git a/invokeai/app/api_app.py b/invokeai/app/api_app.py index 044271779c..1f3a166e62 100644 --- a/invokeai/app/api_app.py +++ b/invokeai/app/api_app.py @@ -16,9 +16,10 @@ from fastapi_events.middleware import EventHandlerASGIMiddleware from pathlib import Path from pydantic.schema import schema -#This should come early so that modules can log their initialization properly +# This should come early so that modules can log their initialization properly from .services.config import InvokeAIAppConfig from ..backend.util.logging import InvokeAILogger + app_config = InvokeAIAppConfig.get_config() app_config.parse_args() logger = InvokeAILogger.getLogger(config=app_config) @@ -27,7 +28,7 @@ from invokeai.version.invokeai_version import __version__ # we call this early so that the message appears before # other invokeai initialization messages if app_config.version: - print(f'InvokeAI version {__version__}') + print(f"InvokeAI version {__version__}") sys.exit(0) import invokeai.frontend.web as web_dir @@ -37,17 +38,18 @@ from .api.dependencies import ApiDependencies from .api.routers import sessions, models, images, boards, board_images, app_info from .api.sockets import SocketIO from .invocations.baseinvocation import BaseInvocation - + import torch import invokeai.backend.util.hotfixes + if torch.backends.mps.is_available(): import invokeai.backend.util.mps_fixes # fix for windows mimetypes registry entries being borked # see https://github.com/invoke-ai/InvokeAI/discussions/3684#discussioncomment-6391352 -mimetypes.add_type('application/javascript', '.js') -mimetypes.add_type('text/css', '.css') +mimetypes.add_type("application/javascript", ".js") +mimetypes.add_type("text/css", ".css") # Create the app # TODO: create this all in a method so configuration/etc. can be passed in? @@ -57,14 +59,13 @@ app = FastAPI(title="Invoke AI", docs_url=None, redoc_url=None) event_handler_id: int = id(app) app.add_middleware( EventHandlerASGIMiddleware, - handlers=[ - local_handler - ], # TODO: consider doing this in services to support different configurations + handlers=[local_handler], # TODO: consider doing this in services to support different configurations middleware_id=event_handler_id, ) socket_io = SocketIO(app) + # Add startup event to load dependencies @app.on_event("startup") async def startup_event(): @@ -76,9 +77,7 @@ async def startup_event(): allow_headers=app_config.allow_headers, ) - ApiDependencies.initialize( - config=app_config, event_handler_id=event_handler_id, logger=logger - ) + ApiDependencies.initialize(config=app_config, event_handler_id=event_handler_id, logger=logger) # Shut down threads @@ -103,7 +102,8 @@ app.include_router(boards.boards_router, prefix="/api") app.include_router(board_images.board_images_router, prefix="/api") -app.include_router(app_info.app_router, prefix='/api') +app.include_router(app_info.app_router, prefix="/api") + # Build a custom OpenAPI to include all outputs # TODO: can outputs be included on metadata of invocation schemas somehow? @@ -144,6 +144,7 @@ def custom_openapi(): invoker_schema["output"] = outputs_ref from invokeai.backend.model_management.models import get_model_config_enums + for model_config_format_enum in set(get_model_config_enums()): name = model_config_format_enum.__qualname__ @@ -166,7 +167,8 @@ def custom_openapi(): app.openapi = custom_openapi # Override API doc favicons -app.mount("/static", StaticFiles(directory=Path(web_dir.__path__[0], 'static/dream_web')), name="static") +app.mount("/static", StaticFiles(directory=Path(web_dir.__path__[0], "static/dream_web")), name="static") + @app.get("/docs", include_in_schema=False) def overridden_swagger(): @@ -187,11 +189,8 @@ def overridden_redoc(): # Must mount *after* the other routes else it borks em -app.mount("/", - StaticFiles(directory=Path(web_dir.__path__[0],"dist"), - html=True - ), name="ui" - ) +app.mount("/", StaticFiles(directory=Path(web_dir.__path__[0], "dist"), html=True), name="ui") + def invoke_api(): def find_port(port: int): @@ -203,10 +202,11 @@ def invoke_api(): return find_port(port=port + 1) else: return port - + from invokeai.backend.install.check_root import check_invokeai_root + check_invokeai_root(app_config) # note, may exit with an exception if root not set up - + port = find_port(app_config.port) if port != app_config.port: logger.warn(f"Port {app_config.port} in use, using port {port}") @@ -217,5 +217,6 @@ def invoke_api(): server = uvicorn.Server(config) loop.run_until_complete(server.serve()) + if __name__ == "__main__": invoke_api() diff --git a/invokeai/app/cli/commands.py b/invokeai/app/cli/commands.py index bffb2988dc..64ea6034fc 100644 --- a/invokeai/app/cli/commands.py +++ b/invokeai/app/cli/commands.py @@ -14,8 +14,14 @@ from ..services.graph import GraphExecutionState, LibraryGraph, Edge from ..services.invoker import Invoker -def add_field_argument(command_parser, name: str, field, default_override = None): - default = default_override if default_override is not None else field.default if field.default_factory is None else field.default_factory() +def add_field_argument(command_parser, name: str, field, default_override=None): + default = ( + default_override + if default_override is not None + else field.default + if field.default_factory is None + else field.default_factory() + ) if get_origin(field.type_) == Literal: allowed_values = get_args(field.type_) allowed_types = set() @@ -47,8 +53,8 @@ def add_parsers( commands: list[type], command_field: str = "type", exclude_fields: list[str] = ["id", "type"], - add_arguments: Union[Callable[[argparse.ArgumentParser], None],None] = None - ): + add_arguments: Union[Callable[[argparse.ArgumentParser], None], None] = None, +): """Adds parsers for each command to the subparsers""" # Create subparsers for each command @@ -61,7 +67,7 @@ def add_parsers( add_arguments(command_parser) # Convert all fields to arguments - fields = command.__fields__ # type: ignore + fields = command.__fields__ # type: ignore for name, field in fields.items(): if name in exclude_fields: continue @@ -70,13 +76,11 @@ def add_parsers( def add_graph_parsers( - subparsers, - graphs: list[LibraryGraph], - add_arguments: Union[Callable[[argparse.ArgumentParser], None], None] = None + subparsers, graphs: list[LibraryGraph], add_arguments: Union[Callable[[argparse.ArgumentParser], None], None] = None ): for graph in graphs: command_parser = subparsers.add_parser(graph.name, help=graph.description) - + if add_arguments is not None: add_arguments(command_parser) @@ -128,6 +132,7 @@ class CliContext: class ExitCli(Exception): """Exception to exit the CLI""" + pass @@ -155,7 +160,7 @@ class BaseCommand(ABC, BaseModel): @classmethod def get_commands_map(cls): # Get the type strings out of the literals and into a dictionary - return dict(map(lambda t: (get_args(get_type_hints(t)['type'])[0], t),BaseCommand.get_all_subclasses())) + return dict(map(lambda t: (get_args(get_type_hints(t)["type"])[0], t), BaseCommand.get_all_subclasses())) @abstractmethod def run(self, context: CliContext) -> None: @@ -165,7 +170,8 @@ class BaseCommand(ABC, BaseModel): class ExitCommand(BaseCommand): """Exits the CLI""" - type: Literal['exit'] = 'exit' + + type: Literal["exit"] = "exit" def run(self, context: CliContext) -> None: raise ExitCli() @@ -173,7 +179,8 @@ class ExitCommand(BaseCommand): class HelpCommand(BaseCommand): """Shows help""" - type: Literal['help'] = 'help' + + type: Literal["help"] = "help" def run(self, context: CliContext) -> None: context.parser.print_help() @@ -183,11 +190,7 @@ def get_graph_execution_history( graph_execution_state: GraphExecutionState, ) -> Iterable[str]: """Gets the history of fully-executed invocations for a graph execution""" - return ( - n - for n in reversed(graph_execution_state.executed_history) - if n in graph_execution_state.graph.nodes - ) + return (n for n in reversed(graph_execution_state.executed_history) if n in graph_execution_state.graph.nodes) def get_invocation_command(invocation) -> str: @@ -218,7 +221,8 @@ def get_invocation_command(invocation) -> str: class HistoryCommand(BaseCommand): """Shows the invocation history""" - type: Literal['history'] = 'history' + + type: Literal["history"] = "history" # Inputs # fmt: off @@ -235,7 +239,8 @@ class HistoryCommand(BaseCommand): class SetDefaultCommand(BaseCommand): """Sets a default value for a field""" - type: Literal['default'] = 'default' + + type: Literal["default"] = "default" # Inputs # fmt: off @@ -253,7 +258,8 @@ class SetDefaultCommand(BaseCommand): class DrawGraphCommand(BaseCommand): """Debugs a graph""" - type: Literal['draw_graph'] = 'draw_graph' + + type: Literal["draw_graph"] = "draw_graph" def run(self, context: CliContext) -> None: session: GraphExecutionState = context.invoker.services.graph_execution_manager.get(context.session.id) @@ -271,7 +277,8 @@ class DrawGraphCommand(BaseCommand): class DrawExecutionGraphCommand(BaseCommand): """Debugs an execution graph""" - type: Literal['draw_xgraph'] = 'draw_xgraph' + + type: Literal["draw_xgraph"] = "draw_xgraph" def run(self, context: CliContext) -> None: session: GraphExecutionState = context.invoker.services.graph_execution_manager.get(context.session.id) @@ -286,6 +293,7 @@ class DrawExecutionGraphCommand(BaseCommand): plt.axis("off") plt.show() + class SortedHelpFormatter(argparse.HelpFormatter): def _iter_indented_subactions(self, action): try: diff --git a/invokeai/app/cli/completer.py b/invokeai/app/cli/completer.py index 79274dab8c..fd10034dd7 100644 --- a/invokeai/app/cli/completer.py +++ b/invokeai/app/cli/completer.py @@ -19,8 +19,8 @@ from ..services.invocation_services import InvocationServices # singleton object, class variable completer = None + class Completer(object): - def __init__(self, model_manager: ModelManager): self.commands = self.get_commands() self.matches = None @@ -43,7 +43,7 @@ class Completer(object): except IndexError: pass options = options or list(self.parse_commands().keys()) - + if not text: # first time self.matches = options else: @@ -56,17 +56,17 @@ class Completer(object): return match @classmethod - def get_commands(self)->List[object]: + def get_commands(self) -> List[object]: """ Return a list of all the client commands and invocations. """ return BaseCommand.get_commands() + BaseInvocation.get_invocations() - def get_current_command(self, buffer: str)->tuple[str, str]: + def get_current_command(self, buffer: str) -> tuple[str, str]: """ Parse the readline buffer to find the most recent command and its switch. """ - if len(buffer)==0: + if len(buffer) == 0: return None, None tokens = shlex.split(buffer) command = None @@ -78,11 +78,11 @@ class Completer(object): else: switch = t # don't try to autocomplete switches that are already complete - if switch and buffer.endswith(' '): - switch=None - return command or '', switch or '' + if switch and buffer.endswith(" "): + switch = None + return command or "", switch or "" - def parse_commands(self)->Dict[str, List[str]]: + def parse_commands(self) -> Dict[str, List[str]]: """ Return a dict in which the keys are the command name and the values are the parameters the command takes. @@ -90,11 +90,11 @@ class Completer(object): result = dict() for command in self.commands: hints = get_type_hints(command) - name = get_args(hints['type'])[0] - result.update({name:hints}) + name = get_args(hints["type"])[0] + result.update({name: hints}) return result - def get_command_options(self, command: str, switch: str)->List[str]: + def get_command_options(self, command: str, switch: str) -> List[str]: """ Return all the parameters that can be passed to the command as command-line switches. Returns None if the command is unrecognized. @@ -102,42 +102,46 @@ class Completer(object): parsed_commands = self.parse_commands() if command not in parsed_commands: return None - + # handle switches in the format "-foo=bar" argument = None - if switch and '=' in switch: - switch, argument = switch.split('=') - - parameter = switch.strip('-') + if switch and "=" in switch: + switch, argument = switch.split("=") + + parameter = switch.strip("-") if parameter in parsed_commands[command]: if argument is None: return self.get_parameter_options(parameter, parsed_commands[command][parameter]) else: - return [f"--{parameter}={x}" for x in self.get_parameter_options(parameter, parsed_commands[command][parameter])] + return [ + f"--{parameter}={x}" + for x in self.get_parameter_options(parameter, parsed_commands[command][parameter]) + ] else: return [f"--{x}" for x in parsed_commands[command].keys()] - def get_parameter_options(self, parameter: str, typehint)->List[str]: + def get_parameter_options(self, parameter: str, typehint) -> List[str]: """ Given a parameter type (such as Literal), offers autocompletions. """ if get_origin(typehint) == Literal: return get_args(typehint) - if parameter == 'model': + if parameter == "model": return self.manager.model_names() - + def _pre_input_hook(self): if self.linebuffer: readline.insert_text(self.linebuffer) readline.redisplay() self.linebuffer = None - + + def set_autocompleter(services: InvocationServices) -> Completer: global completer - + if completer: return completer - + completer = Completer(services.model_manager) readline.set_completer(completer.complete) @@ -162,8 +166,6 @@ def set_autocompleter(services: InvocationServices) -> Completer: pass except OSError: # file likely corrupted newname = f"{histfile}.old" - logger.error( - f"Your history file {histfile} couldn't be loaded and may be corrupted. Renaming it to {newname}" - ) + logger.error(f"Your history file {histfile} couldn't be loaded and may be corrupted. Renaming it to {newname}") histfile.replace(Path(newname)) atexit.register(readline.write_history_file, histfile) diff --git a/invokeai/app/cli_app.py b/invokeai/app/cli_app.py index 341e9e5b7e..bad95bb559 100644 --- a/invokeai/app/cli_app.py +++ b/invokeai/app/cli_app.py @@ -13,6 +13,7 @@ from pydantic.fields import Field # This should come early so that the logger can pick up its configuration options from .services.config import InvokeAIAppConfig from invokeai.backend.util.logging import InvokeAILogger + config = InvokeAIAppConfig.get_config() config.parse_args() logger = InvokeAILogger().getLogger(config=config) @@ -20,7 +21,7 @@ from invokeai.version.invokeai_version import __version__ # we call this early so that the message appears before other invokeai initialization messages if config.version: - print(f'InvokeAI version {__version__}') + print(f"InvokeAI version {__version__}") sys.exit(0) from invokeai.app.services.board_image_record_storage import ( @@ -36,18 +37,21 @@ from invokeai.app.services.image_record_storage import SqliteImageRecordStorage from invokeai.app.services.images import ImageService, ImageServiceDependencies from invokeai.app.services.resource_name import SimpleNameService from invokeai.app.services.urls import LocalUrlService -from .services.default_graphs import (default_text_to_image_graph_id, - create_system_graphs) +from .services.default_graphs import default_text_to_image_graph_id, create_system_graphs from .services.latent_storage import DiskLatentsStorage, ForwardCacheLatentsStorage -from .cli.commands import (BaseCommand, CliContext, ExitCli, - SortedHelpFormatter, add_graph_parsers, add_parsers) +from .cli.commands import BaseCommand, CliContext, ExitCli, SortedHelpFormatter, add_graph_parsers, add_parsers from .cli.completer import set_autocompleter from .invocations.baseinvocation import BaseInvocation from .services.events import EventServiceBase -from .services.graph import (Edge, EdgeConnection, GraphExecutionState, - GraphInvocation, LibraryGraph, - are_connection_types_compatible) +from .services.graph import ( + Edge, + EdgeConnection, + GraphExecutionState, + GraphInvocation, + LibraryGraph, + are_connection_types_compatible, +) from .services.image_file_storage import DiskImageFileStorage from .services.invocation_queue import MemoryInvocationQueue from .services.invocation_services import InvocationServices @@ -58,6 +62,7 @@ from .services.sqlite import SqliteItemStorage import torch import invokeai.backend.util.hotfixes + if torch.backends.mps.is_available(): import invokeai.backend.util.mps_fixes @@ -69,6 +74,7 @@ class CliCommand(BaseModel): class InvalidArgs(Exception): pass + def add_invocation_args(command_parser): # Add linking capability command_parser.add_argument( @@ -113,7 +119,7 @@ def get_command_parser(services: InvocationServices) -> argparse.ArgumentParser: return parser -class NodeField(): +class NodeField: alias: str node_path: str field: str @@ -126,15 +132,20 @@ class NodeField(): self.field_type = field_type -def fields_from_type_hints(hints: dict[str, type], node_path: str) -> dict[str,NodeField]: - return {k:NodeField(alias=k, node_path=node_path, field=k, field_type=v) for k, v in hints.items()} +def fields_from_type_hints(hints: dict[str, type], node_path: str) -> dict[str, NodeField]: + return {k: NodeField(alias=k, node_path=node_path, field=k, field_type=v) for k, v in hints.items()} def get_node_input_field(graph: LibraryGraph, field_alias: str, node_id: str) -> NodeField: """Gets the node field for the specified field alias""" exposed_input = next(e for e in graph.exposed_inputs if e.alias == field_alias) node_type = type(graph.graph.get_node(exposed_input.node_path)) - return NodeField(alias=exposed_input.alias, node_path=f'{node_id}.{exposed_input.node_path}', field=exposed_input.field, field_type=get_type_hints(node_type)[exposed_input.field]) + return NodeField( + alias=exposed_input.alias, + node_path=f"{node_id}.{exposed_input.node_path}", + field=exposed_input.field, + field_type=get_type_hints(node_type)[exposed_input.field], + ) def get_node_output_field(graph: LibraryGraph, field_alias: str, node_id: str) -> NodeField: @@ -142,7 +153,12 @@ def get_node_output_field(graph: LibraryGraph, field_alias: str, node_id: str) - exposed_output = next(e for e in graph.exposed_outputs if e.alias == field_alias) node_type = type(graph.graph.get_node(exposed_output.node_path)) node_output_type = node_type.get_output_type() - return NodeField(alias=exposed_output.alias, node_path=f'{node_id}.{exposed_output.node_path}', field=exposed_output.field, field_type=get_type_hints(node_output_type)[exposed_output.field]) + return NodeField( + alias=exposed_output.alias, + node_path=f"{node_id}.{exposed_output.node_path}", + field=exposed_output.field, + field_type=get_type_hints(node_output_type)[exposed_output.field], + ) def get_node_inputs(invocation: BaseInvocation, context: CliContext) -> dict[str, NodeField]: @@ -165,9 +181,7 @@ def get_node_outputs(invocation: BaseInvocation, context: CliContext) -> dict[st return {e.alias: get_node_output_field(graph, e.alias, invocation.id) for e in graph.exposed_outputs} -def generate_matching_edges( - a: BaseInvocation, b: BaseInvocation, context: CliContext -) -> list[Edge]: +def generate_matching_edges(a: BaseInvocation, b: BaseInvocation, context: CliContext) -> list[Edge]: """Generates all possible edges between two invocations""" afields = get_node_outputs(a, context) bfields = get_node_inputs(b, context) @@ -179,12 +193,14 @@ def generate_matching_edges( matching_fields = matching_fields.difference(invalid_fields) # Validate types - matching_fields = [f for f in matching_fields if are_connection_types_compatible(afields[f].field_type, bfields[f].field_type)] + matching_fields = [ + f for f in matching_fields if are_connection_types_compatible(afields[f].field_type, bfields[f].field_type) + ] edges = [ Edge( source=EdgeConnection(node_id=afields[alias].node_path, field=afields[alias].field), - destination=EdgeConnection(node_id=bfields[alias].node_path, field=bfields[alias].field) + destination=EdgeConnection(node_id=bfields[alias].node_path, field=bfields[alias].field), ) for alias in matching_fields ] @@ -193,6 +209,7 @@ def generate_matching_edges( class SessionError(Exception): """Raised when a session error has occurred""" + pass @@ -209,22 +226,23 @@ def invoke_all(context: CliContext): context.invoker.services.logger.error( f"Error in node {n} (source node {context.session.prepared_source_mapping[n]}): {context.session.errors[n]}" ) - + raise SessionError() + def invoke_cli(): - logger.info(f'InvokeAI version {__version__}') + logger.info(f"InvokeAI version {__version__}") # get the optional list of invocations to execute on the command line parser = config.get_parser() - parser.add_argument('commands',nargs='*') + parser.add_argument("commands", nargs="*") invocation_commands = parser.parse_args().commands # get the optional file to read commands from. # Simplest is to use it for STDIN if infile := config.from_file: - sys.stdin = open(infile,"r") - - model_manager = ModelManagerService(config,logger) + sys.stdin = open(infile, "r") + + model_manager = ModelManagerService(config, logger) events = EventServiceBase() output_folder = config.output_path @@ -234,13 +252,13 @@ def invoke_cli(): db_location = ":memory:" else: db_location = config.db_path - db_location.parent.mkdir(parents=True,exist_ok=True) + db_location.parent.mkdir(parents=True, exist_ok=True) logger.info(f'InvokeAI database location is "{db_location}"') graph_execution_manager = SqliteItemStorage[GraphExecutionState]( - filename=db_location, table_name="graph_executions" - ) + filename=db_location, table_name="graph_executions" + ) urls = LocalUrlService() image_record_storage = SqliteImageRecordStorage(db_location) @@ -281,24 +299,21 @@ def invoke_cli(): graph_execution_manager=graph_execution_manager, ) ) - + services = InvocationServices( model_manager=model_manager, events=events, - latents = ForwardCacheLatentsStorage(DiskLatentsStorage(f'{output_folder}/latents')), + latents=ForwardCacheLatentsStorage(DiskLatentsStorage(f"{output_folder}/latents")), images=images, boards=boards, board_images=board_images, queue=MemoryInvocationQueue(), - graph_library=SqliteItemStorage[LibraryGraph]( - filename=db_location, table_name="graphs" - ), + graph_library=SqliteItemStorage[LibraryGraph](filename=db_location, table_name="graphs"), graph_execution_manager=graph_execution_manager, processor=DefaultInvocationProcessor(), logger=logger, configuration=config, ) - system_graphs = create_system_graphs(services.graph_library) system_graph_names = set([g.name for g in system_graphs]) @@ -308,7 +323,7 @@ def invoke_cli(): session: GraphExecutionState = invoker.create_execution_state() parser = get_command_parser(services) - re_negid = re.compile('^-[0-9]+$') + re_negid = re.compile("^-[0-9]+$") # Uncomment to print out previous sessions at startup # print(services.session_manager.list()) @@ -318,7 +333,7 @@ def invoke_cli(): command_line_args_exist = len(invocation_commands) > 0 done = False - + while not done: try: if command_line_args_exist: @@ -332,7 +347,7 @@ def invoke_cli(): try: # Refresh the state of the session - #history = list(get_graph_execution_history(context.session)) + # history = list(get_graph_execution_history(context.session)) history = list(reversed(context.nodes_added)) # Split the command for piping @@ -353,17 +368,17 @@ def invoke_cli(): args[field_name] = field_default # Parse invocation - command: CliCommand = None # type:ignore + command: CliCommand = None # type:ignore system_graph: Optional[LibraryGraph] = None - if args['type'] in system_graph_names: - system_graph = next(filter(lambda g: g.name == args['type'], system_graphs)) + if args["type"] in system_graph_names: + system_graph = next(filter(lambda g: g.name == args["type"], system_graphs)) invocation = GraphInvocation(graph=system_graph.graph, id=str(current_id)) for exposed_input in system_graph.exposed_inputs: if exposed_input.alias in args: node = invocation.graph.get_node(exposed_input.node_path) field = exposed_input.field setattr(node, field, args[exposed_input.alias]) - command = CliCommand(command = invocation) + command = CliCommand(command=invocation) context.graph_nodes[invocation.id] = system_graph.id else: args["id"] = current_id @@ -385,17 +400,13 @@ def invoke_cli(): # Pipe previous command output (if there was a previous command) edges: list[Edge] = list() if len(history) > 0 or current_id != start_id: - from_id = ( - history[0] if current_id == start_id else str(current_id - 1) - ) + from_id = history[0] if current_id == start_id else str(current_id - 1) from_node = ( next(filter(lambda n: n[0].id == from_id, new_invocations))[0] if current_id != start_id else context.session.graph.get_node(from_id) ) - matching_edges = generate_matching_edges( - from_node, command.command, context - ) + matching_edges = generate_matching_edges(from_node, command.command, context) edges.extend(matching_edges) # Parse provided links @@ -406,16 +417,18 @@ def invoke_cli(): node_id = str(current_id + int(node_id)) link_node = context.session.graph.get_node(node_id) - matching_edges = generate_matching_edges( - link_node, command.command, context - ) + matching_edges = generate_matching_edges(link_node, command.command, context) matching_destinations = [e.destination for e in matching_edges] edges = [e for e in edges if e.destination not in matching_destinations] edges.extend(matching_edges) if "link" in args and args["link"]: for link in args["link"]: - edges = [e for e in edges if e.destination.node_id != command.command.id or e.destination.field != link[2]] + edges = [ + e + for e in edges + if e.destination.node_id != command.command.id or e.destination.field != link[2] + ] node_id = link[0] if re_negid.match(node_id): @@ -428,7 +441,7 @@ def invoke_cli(): edges.append( Edge( source=EdgeConnection(node_id=node_output.node_path, field=node_output.field), - destination=EdgeConnection(node_id=node_input.node_path, field=node_input.field) + destination=EdgeConnection(node_id=node_input.node_path, field=node_input.field), ) ) diff --git a/invokeai/app/invocations/__init__.py b/invokeai/app/invocations/__init__.py index 0a451ff618..6407a1cdee 100644 --- a/invokeai/app/invocations/__init__.py +++ b/invokeai/app/invocations/__init__.py @@ -4,9 +4,5 @@ __all__ = [] dirname = os.path.dirname(os.path.abspath(__file__)) for f in os.listdir(dirname): - if ( - f != "__init__.py" - and os.path.isfile("%s/%s" % (dirname, f)) - and f[-3:] == ".py" - ): + if f != "__init__.py" and os.path.isfile("%s/%s" % (dirname, f)) and f[-3:] == ".py": __all__.append(f[:-3]) diff --git a/invokeai/app/invocations/baseinvocation.py b/invokeai/app/invocations/baseinvocation.py index 4c7314bd2b..758ab2e787 100644 --- a/invokeai/app/invocations/baseinvocation.py +++ b/invokeai/app/invocations/baseinvocation.py @@ -4,8 +4,7 @@ from __future__ import annotations from abc import ABC, abstractmethod from inspect import signature -from typing import (TYPE_CHECKING, Dict, List, Literal, TypedDict, get_args, - get_type_hints) +from typing import TYPE_CHECKING, Dict, List, Literal, TypedDict, get_args, get_type_hints from pydantic import BaseConfig, BaseModel, Field diff --git a/invokeai/app/invocations/collections.py b/invokeai/app/invocations/collections.py index 5446757eb0..01c003da96 100644 --- a/invokeai/app/invocations/collections.py +++ b/invokeai/app/invocations/collections.py @@ -8,8 +8,7 @@ from pydantic import Field, validator from invokeai.app.models.image import ImageField from invokeai.app.util.misc import SEED_MAX, get_random_seed -from .baseinvocation import (BaseInvocation, BaseInvocationOutput, - InvocationConfig, InvocationContext, UIConfig) +from .baseinvocation import BaseInvocation, BaseInvocationOutput, InvocationConfig, InvocationContext, UIConfig class IntCollectionOutput(BaseInvocationOutput): @@ -27,8 +26,7 @@ class FloatCollectionOutput(BaseInvocationOutput): type: Literal["float_collection"] = "float_collection" # Outputs - collection: list[float] = Field( - default=[], description="The float collection") + collection: list[float] = Field(default=[], description="The float collection") class ImageCollectionOutput(BaseInvocationOutput): @@ -37,8 +35,7 @@ class ImageCollectionOutput(BaseInvocationOutput): type: Literal["image_collection"] = "image_collection" # Outputs - collection: list[ImageField] = Field( - default=[], description="The output images") + collection: list[ImageField] = Field(default=[], description="The output images") class Config: schema_extra = {"required": ["type", "collection"]} @@ -56,10 +53,7 @@ class RangeInvocation(BaseInvocation): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Range", - "tags": ["range", "integer", "collection"] - }, + "ui": {"title": "Range", "tags": ["range", "integer", "collection"]}, } @validator("stop") @@ -69,9 +63,7 @@ class RangeInvocation(BaseInvocation): return v def invoke(self, context: InvocationContext) -> IntCollectionOutput: - return IntCollectionOutput( - collection=list(range(self.start, self.stop, self.step)) - ) + return IntCollectionOutput(collection=list(range(self.start, self.stop, self.step))) class RangeOfSizeInvocation(BaseInvocation): @@ -86,18 +78,11 @@ class RangeOfSizeInvocation(BaseInvocation): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Sized Range", - "tags": ["range", "integer", "size", "collection"] - }, + "ui": {"title": "Sized Range", "tags": ["range", "integer", "size", "collection"]}, } def invoke(self, context: InvocationContext) -> IntCollectionOutput: - return IntCollectionOutput( - collection=list( - range( - self.start, self.start + self.size, - self.step))) + return IntCollectionOutput(collection=list(range(self.start, self.start + self.size, self.step))) class RandomRangeInvocation(BaseInvocation): @@ -107,9 +92,7 @@ class RandomRangeInvocation(BaseInvocation): # Inputs low: int = Field(default=0, description="The inclusive low value") - high: int = Field( - default=np.iinfo(np.int32).max, description="The exclusive high value" - ) + high: int = Field(default=np.iinfo(np.int32).max, description="The exclusive high value") size: int = Field(default=1, description="The number of values to generate") seed: int = Field( ge=0, @@ -120,19 +103,12 @@ class RandomRangeInvocation(BaseInvocation): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Random Range", - "tags": ["range", "integer", "random", "collection"] - }, + "ui": {"title": "Random Range", "tags": ["range", "integer", "random", "collection"]}, } def invoke(self, context: InvocationContext) -> IntCollectionOutput: rng = np.random.default_rng(self.seed) - return IntCollectionOutput( - collection=list( - rng.integers( - low=self.low, high=self.high, - size=self.size))) + return IntCollectionOutput(collection=list(rng.integers(low=self.low, high=self.high, size=self.size))) class ImageCollectionInvocation(BaseInvocation): diff --git a/invokeai/app/invocations/compel.py b/invokeai/app/invocations/compel.py index 6aadbf509d..fb29e01628 100644 --- a/invokeai/app/invocations/compel.py +++ b/invokeai/app/invocations/compel.py @@ -3,64 +3,63 @@ from pydantic import BaseModel, Field import re import torch from compel import Compel, ReturnedEmbeddingsType -from compel.prompt_parser import (Blend, Conjunction, - CrossAttentionControlSubstitute, - FlattenedPrompt, Fragment) +from compel.prompt_parser import Blend, Conjunction, CrossAttentionControlSubstitute, FlattenedPrompt, Fragment from ...backend.util.devices import torch_dtype from ...backend.model_management import ModelType from ...backend.model_management.models import ModelNotFoundException from ...backend.model_management.lora import ModelPatcher from ...backend.stable_diffusion.diffusion import InvokeAIDiffuserComponent -from .baseinvocation import (BaseInvocation, BaseInvocationOutput, - InvocationConfig, InvocationContext) +from .baseinvocation import BaseInvocation, BaseInvocationOutput, InvocationConfig, InvocationContext from .model import ClipField from dataclasses import dataclass class ConditioningField(BaseModel): - conditioning_name: Optional[str] = Field( - default=None, description="The name of conditioning data") + conditioning_name: Optional[str] = Field(default=None, description="The name of conditioning data") class Config: schema_extra = {"required": ["conditioning_name"]} + @dataclass class BasicConditioningInfo: - #type: Literal["basic_conditioning"] = "basic_conditioning" + # type: Literal["basic_conditioning"] = "basic_conditioning" embeds: torch.Tensor extra_conditioning: Optional[InvokeAIDiffuserComponent.ExtraConditioningInfo] # weight: float # mode: ConditioningAlgo + @dataclass class SDXLConditioningInfo(BasicConditioningInfo): - #type: Literal["sdxl_conditioning"] = "sdxl_conditioning" + # type: Literal["sdxl_conditioning"] = "sdxl_conditioning" pooled_embeds: torch.Tensor add_time_ids: torch.Tensor -ConditioningInfoType = Annotated[ - Union[BasicConditioningInfo, SDXLConditioningInfo], - Field(discriminator="type") -] + +ConditioningInfoType = Annotated[Union[BasicConditioningInfo, SDXLConditioningInfo], Field(discriminator="type")] + @dataclass class ConditioningFieldData: conditionings: List[Union[BasicConditioningInfo, SDXLConditioningInfo]] - #unconditioned: Optional[torch.Tensor] + # unconditioned: Optional[torch.Tensor] -#class ConditioningAlgo(str, Enum): + +# class ConditioningAlgo(str, Enum): # Compose = "compose" # ComposeEx = "compose_ex" # PerpNeg = "perp_neg" + class CompelOutput(BaseInvocationOutput): """Compel parser output""" - #fmt: off + # fmt: off type: Literal["compel_output"] = "compel_output" conditioning: ConditioningField = Field(default=None, description="Conditioning") - #fmt: on + # fmt: on class CompelInvocation(BaseInvocation): @@ -74,33 +73,28 @@ class CompelInvocation(BaseInvocation): # Schema customisation class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Prompt (Compel)", - "tags": ["prompt", "compel"], - "type_hints": { - "model": "model" - } - }, + "ui": {"title": "Prompt (Compel)", "tags": ["prompt", "compel"], "type_hints": {"model": "model"}}, } @torch.no_grad() def invoke(self, context: InvocationContext) -> CompelOutput: tokenizer_info = context.services.model_manager.get_model( - **self.clip.tokenizer.dict(), context=context, + **self.clip.tokenizer.dict(), + context=context, ) text_encoder_info = context.services.model_manager.get_model( - **self.clip.text_encoder.dict(), context=context, + **self.clip.text_encoder.dict(), + context=context, ) def _lora_loader(): for lora in self.clip.loras: - lora_info = context.services.model_manager.get_model( - **lora.dict(exclude={"weight"}), context=context) + lora_info = context.services.model_manager.get_model(**lora.dict(exclude={"weight"}), context=context) yield (lora_info.context.model, lora.weight) del lora_info return - #loras = [(context.services.model_manager.get_model(**lora.dict(exclude={"weight"})).context.model, lora.weight) for lora in self.clip.loras] + # loras = [(context.services.model_manager.get_model(**lora.dict(exclude={"weight"})).context.model, lora.weight) for lora in self.clip.loras] ti_list = [] for trigger in re.findall(r"<[a-zA-Z0-9., _-]+>", self.prompt): @@ -116,15 +110,18 @@ class CompelInvocation(BaseInvocation): ) except ModelNotFoundException: # print(e) - #import traceback - #print(traceback.format_exc()) - print(f"Warn: trigger: \"{trigger}\" not found") - - with ModelPatcher.apply_lora_text_encoder(text_encoder_info.context.model, _lora_loader()),\ - ModelPatcher.apply_ti(tokenizer_info.context.model, text_encoder_info.context.model, ti_list) as (tokenizer, ti_manager),\ - ModelPatcher.apply_clip_skip(text_encoder_info.context.model, self.clip.skipped_layers),\ - text_encoder_info as text_encoder: + # import traceback + # print(traceback.format_exc()) + print(f'Warn: trigger: "{trigger}" not found') + with ModelPatcher.apply_lora_text_encoder( + text_encoder_info.context.model, _lora_loader() + ), ModelPatcher.apply_ti(tokenizer_info.context.model, text_encoder_info.context.model, ti_list) as ( + tokenizer, + ti_manager, + ), ModelPatcher.apply_clip_skip( + text_encoder_info.context.model, self.clip.skipped_layers + ), text_encoder_info as text_encoder: compel = Compel( tokenizer=tokenizer, text_encoder=text_encoder, @@ -139,14 +136,12 @@ class CompelInvocation(BaseInvocation): if context.services.configuration.log_tokenization: log_tokenization_for_prompt_object(prompt, tokenizer) - c, options = compel.build_conditioning_tensor_for_prompt_object( - prompt) + c, options = compel.build_conditioning_tensor_for_prompt_object(prompt) ec = InvokeAIDiffuserComponent.ExtraConditioningInfo( - tokens_count_including_eos_bos=get_max_token_count( - tokenizer, conjunction), - cross_attention_control_args=options.get( - "cross_attention_control", None),) + tokens_count_including_eos_bos=get_max_token_count(tokenizer, conjunction), + cross_attention_control_args=options.get("cross_attention_control", None), + ) c = c.detach().to("cpu") @@ -168,24 +163,26 @@ class CompelInvocation(BaseInvocation): ), ) + class SDXLPromptInvocationBase: def run_clip_raw(self, context, clip_field, prompt, get_pooled): tokenizer_info = context.services.model_manager.get_model( - **clip_field.tokenizer.dict(), context=context, + **clip_field.tokenizer.dict(), + context=context, ) text_encoder_info = context.services.model_manager.get_model( - **clip_field.text_encoder.dict(), context=context, + **clip_field.text_encoder.dict(), + context=context, ) def _lora_loader(): for lora in clip_field.loras: - lora_info = context.services.model_manager.get_model( - **lora.dict(exclude={"weight"}), context=context) + lora_info = context.services.model_manager.get_model(**lora.dict(exclude={"weight"}), context=context) yield (lora_info.context.model, lora.weight) del lora_info return - #loras = [(context.services.model_manager.get_model(**lora.dict(exclude={"weight"})).context.model, lora.weight) for lora in self.clip.loras] + # loras = [(context.services.model_manager.get_model(**lora.dict(exclude={"weight"})).context.model, lora.weight) for lora in self.clip.loras] ti_list = [] for trigger in re.findall(r"<[a-zA-Z0-9., _-]+>", prompt): @@ -201,15 +198,18 @@ class SDXLPromptInvocationBase: ) except ModelNotFoundException: # print(e) - #import traceback - #print(traceback.format_exc()) - print(f"Warn: trigger: \"{trigger}\" not found") - - with ModelPatcher.apply_lora_text_encoder(text_encoder_info.context.model, _lora_loader()),\ - ModelPatcher.apply_ti(tokenizer_info.context.model, text_encoder_info.context.model, ti_list) as (tokenizer, ti_manager),\ - ModelPatcher.apply_clip_skip(text_encoder_info.context.model, clip_field.skipped_layers),\ - text_encoder_info as text_encoder: + # import traceback + # print(traceback.format_exc()) + print(f'Warn: trigger: "{trigger}" not found') + with ModelPatcher.apply_lora_text_encoder( + text_encoder_info.context.model, _lora_loader() + ), ModelPatcher.apply_ti(tokenizer_info.context.model, text_encoder_info.context.model, ti_list) as ( + tokenizer, + ti_manager, + ), ModelPatcher.apply_clip_skip( + text_encoder_info.context.model, clip_field.skipped_layers + ), text_encoder_info as text_encoder: text_inputs = tokenizer( prompt, padding="max_length", @@ -241,21 +241,22 @@ class SDXLPromptInvocationBase: def run_clip_compel(self, context, clip_field, prompt, get_pooled): tokenizer_info = context.services.model_manager.get_model( - **clip_field.tokenizer.dict(), context=context, + **clip_field.tokenizer.dict(), + context=context, ) text_encoder_info = context.services.model_manager.get_model( - **clip_field.text_encoder.dict(), context=context, + **clip_field.text_encoder.dict(), + context=context, ) def _lora_loader(): for lora in clip_field.loras: - lora_info = context.services.model_manager.get_model( - **lora.dict(exclude={"weight"}), context=context) + lora_info = context.services.model_manager.get_model(**lora.dict(exclude={"weight"}), context=context) yield (lora_info.context.model, lora.weight) del lora_info return - #loras = [(context.services.model_manager.get_model(**lora.dict(exclude={"weight"})).context.model, lora.weight) for lora in self.clip.loras] + # loras = [(context.services.model_manager.get_model(**lora.dict(exclude={"weight"})).context.model, lora.weight) for lora in self.clip.loras] ti_list = [] for trigger in re.findall(r"<[a-zA-Z0-9., _-]+>", prompt): @@ -271,22 +272,25 @@ class SDXLPromptInvocationBase: ) except ModelNotFoundException: # print(e) - #import traceback - #print(traceback.format_exc()) - print(f"Warn: trigger: \"{trigger}\" not found") - - with ModelPatcher.apply_lora_text_encoder(text_encoder_info.context.model, _lora_loader()),\ - ModelPatcher.apply_ti(tokenizer_info.context.model, text_encoder_info.context.model, ti_list) as (tokenizer, ti_manager),\ - ModelPatcher.apply_clip_skip(text_encoder_info.context.model, clip_field.skipped_layers),\ - text_encoder_info as text_encoder: + # import traceback + # print(traceback.format_exc()) + print(f'Warn: trigger: "{trigger}" not found') + with ModelPatcher.apply_lora_text_encoder( + text_encoder_info.context.model, _lora_loader() + ), ModelPatcher.apply_ti(tokenizer_info.context.model, text_encoder_info.context.model, ti_list) as ( + tokenizer, + ti_manager, + ), ModelPatcher.apply_clip_skip( + text_encoder_info.context.model, clip_field.skipped_layers + ), text_encoder_info as text_encoder: compel = Compel( tokenizer=tokenizer, text_encoder=text_encoder, textual_inversion_manager=ti_manager, dtype_for_device_getter=torch_dtype, truncate_long_prompts=True, # TODO: - returned_embeddings_type=ReturnedEmbeddingsType.PENULTIMATE_HIDDEN_STATES_NON_NORMALIZED, # TODO: clip skip + returned_embeddings_type=ReturnedEmbeddingsType.PENULTIMATE_HIDDEN_STATES_NON_NORMALIZED, # TODO: clip skip requires_pooled=True, ) @@ -320,6 +324,7 @@ class SDXLPromptInvocationBase: return c, c_pooled, ec + class SDXLCompelPromptInvocation(BaseInvocation, SDXLPromptInvocationBase): """Parse prompt using compel package to conditioning.""" @@ -339,13 +344,7 @@ class SDXLCompelPromptInvocation(BaseInvocation, SDXLPromptInvocationBase): # Schema customisation class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "SDXL Prompt (Compel)", - "tags": ["prompt", "compel"], - "type_hints": { - "model": "model" - } - }, + "ui": {"title": "SDXL Prompt (Compel)", "tags": ["prompt", "compel"], "type_hints": {"model": "model"}}, } @torch.no_grad() @@ -360,9 +359,7 @@ class SDXLCompelPromptInvocation(BaseInvocation, SDXLPromptInvocationBase): crop_coords = (self.crop_top, self.crop_left) target_size = (self.target_height, self.target_width) - add_time_ids = torch.tensor([ - original_size + crop_coords + target_size - ]) + add_time_ids = torch.tensor([original_size + crop_coords + target_size]) conditioning_data = ConditioningFieldData( conditionings=[ @@ -384,12 +381,13 @@ class SDXLCompelPromptInvocation(BaseInvocation, SDXLPromptInvocationBase): ), ) + class SDXLRefinerCompelPromptInvocation(BaseInvocation, SDXLPromptInvocationBase): """Parse prompt using compel package to conditioning.""" type: Literal["sdxl_refiner_compel_prompt"] = "sdxl_refiner_compel_prompt" - style: str = Field(default="", description="Style prompt") # TODO: ? + style: str = Field(default="", description="Style prompt") # TODO: ? original_width: int = Field(1024, description="") original_height: int = Field(1024, description="") crop_top: int = Field(0, description="") @@ -403,9 +401,7 @@ class SDXLRefinerCompelPromptInvocation(BaseInvocation, SDXLPromptInvocationBase "ui": { "title": "SDXL Refiner Prompt (Compel)", "tags": ["prompt", "compel"], - "type_hints": { - "model": "model" - } + "type_hints": {"model": "model"}, }, } @@ -416,9 +412,7 @@ class SDXLRefinerCompelPromptInvocation(BaseInvocation, SDXLPromptInvocationBase original_size = (self.original_height, self.original_width) crop_coords = (self.crop_top, self.crop_left) - add_time_ids = torch.tensor([ - original_size + crop_coords + (self.aesthetic_score,) - ]) + add_time_ids = torch.tensor([original_size + crop_coords + (self.aesthetic_score,)]) conditioning_data = ConditioningFieldData( conditionings=[ @@ -426,7 +420,7 @@ class SDXLRefinerCompelPromptInvocation(BaseInvocation, SDXLPromptInvocationBase embeds=c2, pooled_embeds=c2_pooled, add_time_ids=add_time_ids, - extra_conditioning=ec2, # or None + extra_conditioning=ec2, # or None ) ] ) @@ -440,6 +434,7 @@ class SDXLRefinerCompelPromptInvocation(BaseInvocation, SDXLPromptInvocationBase ), ) + class SDXLRawPromptInvocation(BaseInvocation, SDXLPromptInvocationBase): """Pass unmodified prompt to conditioning without compel processing.""" @@ -459,13 +454,7 @@ class SDXLRawPromptInvocation(BaseInvocation, SDXLPromptInvocationBase): # Schema customisation class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "SDXL Prompt (Raw)", - "tags": ["prompt", "compel"], - "type_hints": { - "model": "model" - } - }, + "ui": {"title": "SDXL Prompt (Raw)", "tags": ["prompt", "compel"], "type_hints": {"model": "model"}}, } @torch.no_grad() @@ -480,9 +469,7 @@ class SDXLRawPromptInvocation(BaseInvocation, SDXLPromptInvocationBase): crop_coords = (self.crop_top, self.crop_left) target_size = (self.target_height, self.target_width) - add_time_ids = torch.tensor([ - original_size + crop_coords + target_size - ]) + add_time_ids = torch.tensor([original_size + crop_coords + target_size]) conditioning_data = ConditioningFieldData( conditionings=[ @@ -504,12 +491,13 @@ class SDXLRawPromptInvocation(BaseInvocation, SDXLPromptInvocationBase): ), ) + class SDXLRefinerRawPromptInvocation(BaseInvocation, SDXLPromptInvocationBase): """Parse prompt using compel package to conditioning.""" type: Literal["sdxl_refiner_raw_prompt"] = "sdxl_refiner_raw_prompt" - style: str = Field(default="", description="Style prompt") # TODO: ? + style: str = Field(default="", description="Style prompt") # TODO: ? original_width: int = Field(1024, description="") original_height: int = Field(1024, description="") crop_top: int = Field(0, description="") @@ -523,9 +511,7 @@ class SDXLRefinerRawPromptInvocation(BaseInvocation, SDXLPromptInvocationBase): "ui": { "title": "SDXL Refiner Prompt (Raw)", "tags": ["prompt", "compel"], - "type_hints": { - "model": "model" - } + "type_hints": {"model": "model"}, }, } @@ -536,9 +522,7 @@ class SDXLRefinerRawPromptInvocation(BaseInvocation, SDXLPromptInvocationBase): original_size = (self.original_height, self.original_width) crop_coords = (self.crop_top, self.crop_left) - add_time_ids = torch.tensor([ - original_size + crop_coords + (self.aesthetic_score,) - ]) + add_time_ids = torch.tensor([original_size + crop_coords + (self.aesthetic_score,)]) conditioning_data = ConditioningFieldData( conditionings=[ @@ -546,7 +530,7 @@ class SDXLRefinerRawPromptInvocation(BaseInvocation, SDXLPromptInvocationBase): embeds=c2, pooled_embeds=c2_pooled, add_time_ids=add_time_ids, - extra_conditioning=ec2, # or None + extra_conditioning=ec2, # or None ) ] ) @@ -563,11 +547,14 @@ class SDXLRefinerRawPromptInvocation(BaseInvocation, SDXLPromptInvocationBase): class ClipSkipInvocationOutput(BaseInvocationOutput): """Clip skip node output""" + type: Literal["clip_skip_output"] = "clip_skip_output" clip: ClipField = Field(None, description="Clip with skipped layers") + class ClipSkipInvocation(BaseInvocation): """Skip layers in clip text_encoder model.""" + type: Literal["clip_skip"] = "clip_skip" clip: ClipField = Field(None, description="Clip to use") @@ -575,10 +562,7 @@ class ClipSkipInvocation(BaseInvocation): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "CLIP Skip", - "tags": ["clip", "skip"] - }, + "ui": {"title": "CLIP Skip", "tags": ["clip", "skip"]}, } def invoke(self, context: InvocationContext) -> ClipSkipInvocationOutput: @@ -589,46 +573,26 @@ class ClipSkipInvocation(BaseInvocation): def get_max_token_count( - tokenizer, prompt: Union[FlattenedPrompt, Blend, Conjunction], - truncate_if_too_long=False) -> int: + tokenizer, prompt: Union[FlattenedPrompt, Blend, Conjunction], truncate_if_too_long=False +) -> int: if type(prompt) is Blend: blend: Blend = prompt - return max( - [ - get_max_token_count(tokenizer, p, truncate_if_too_long) - for p in blend.prompts - ] - ) + return max([get_max_token_count(tokenizer, p, truncate_if_too_long) for p in blend.prompts]) elif type(prompt) is Conjunction: conjunction: Conjunction = prompt - return sum( - [ - get_max_token_count(tokenizer, p, truncate_if_too_long) - for p in conjunction.prompts - ] - ) + return sum([get_max_token_count(tokenizer, p, truncate_if_too_long) for p in conjunction.prompts]) else: - return len( - get_tokens_for_prompt_object( - tokenizer, prompt, truncate_if_too_long)) + return len(get_tokens_for_prompt_object(tokenizer, prompt, truncate_if_too_long)) -def get_tokens_for_prompt_object( - tokenizer, parsed_prompt: FlattenedPrompt, truncate_if_too_long=True -) -> List[str]: +def get_tokens_for_prompt_object(tokenizer, parsed_prompt: FlattenedPrompt, truncate_if_too_long=True) -> List[str]: if type(parsed_prompt) is Blend: - raise ValueError( - "Blend is not supported here - you need to get tokens for each of its .children" - ) + raise ValueError("Blend is not supported here - you need to get tokens for each of its .children") text_fragments = [ x.text if type(x) is Fragment - else ( - " ".join([f.text for f in x.original]) - if type(x) is CrossAttentionControlSubstitute - else str(x) - ) + else (" ".join([f.text for f in x.original]) if type(x) is CrossAttentionControlSubstitute else str(x)) for x in parsed_prompt.children ] text = " ".join(text_fragments) @@ -639,25 +603,17 @@ def get_tokens_for_prompt_object( return tokens -def log_tokenization_for_conjunction( - c: Conjunction, tokenizer, display_label_prefix=None -): +def log_tokenization_for_conjunction(c: Conjunction, tokenizer, display_label_prefix=None): display_label_prefix = display_label_prefix or "" for i, p in enumerate(c.prompts): if len(c.prompts) > 1: this_display_label_prefix = f"{display_label_prefix}(conjunction part {i + 1}, weight={c.weights[i]})" else: this_display_label_prefix = display_label_prefix - log_tokenization_for_prompt_object( - p, - tokenizer, - display_label_prefix=this_display_label_prefix - ) + log_tokenization_for_prompt_object(p, tokenizer, display_label_prefix=this_display_label_prefix) -def log_tokenization_for_prompt_object( - p: Union[Blend, FlattenedPrompt], tokenizer, display_label_prefix=None -): +def log_tokenization_for_prompt_object(p: Union[Blend, FlattenedPrompt], tokenizer, display_label_prefix=None): display_label_prefix = display_label_prefix or "" if type(p) is Blend: blend: Blend = p @@ -694,13 +650,10 @@ def log_tokenization_for_prompt_object( ) else: text = " ".join([x.text for x in flattened_prompt.children]) - log_tokenization_for_text( - text, tokenizer, display_label=display_label_prefix - ) + log_tokenization_for_text(text, tokenizer, display_label=display_label_prefix) -def log_tokenization_for_text( - text, tokenizer, display_label=None, truncate_if_too_long=False): +def log_tokenization_for_text(text, tokenizer, display_label=None, truncate_if_too_long=False): """shows how the prompt is tokenized # usually tokens have '' to indicate end-of-word, # but for readability it has been replaced with ' ' diff --git a/invokeai/app/invocations/controlnet_image_processors.py b/invokeai/app/invocations/controlnet_image_processors.py index 2087594b7b..d2b2d44526 100644 --- a/invokeai/app/invocations/controlnet_image_processors.py +++ b/invokeai/app/invocations/controlnet_image_processors.py @@ -6,20 +6,29 @@ from typing import Dict, List, Literal, Optional, Union import cv2 import numpy as np -from controlnet_aux import (CannyDetector, ContentShuffleDetector, HEDdetector, - LeresDetector, LineartAnimeDetector, - LineartDetector, MediapipeFaceDetector, - MidasDetector, MLSDdetector, NormalBaeDetector, - OpenposeDetector, PidiNetDetector, SamDetector, - ZoeDetector) +from controlnet_aux import ( + CannyDetector, + ContentShuffleDetector, + HEDdetector, + LeresDetector, + LineartAnimeDetector, + LineartDetector, + MediapipeFaceDetector, + MidasDetector, + MLSDdetector, + NormalBaeDetector, + OpenposeDetector, + PidiNetDetector, + SamDetector, + ZoeDetector, +) from controlnet_aux.util import HWC3, ade_palette from PIL import Image from pydantic import BaseModel, Field, validator from ...backend.model_management import BaseModelType, ModelType from ..models.image import ImageCategory, ImageField, ResourceOrigin -from .baseinvocation import (BaseInvocation, BaseInvocationOutput, - InvocationConfig, InvocationContext) +from .baseinvocation import BaseInvocation, BaseInvocationOutput, InvocationConfig, InvocationContext from ..models.image import ImageOutput, PILInvocationConfig CONTROLNET_DEFAULT_MODELS = [ @@ -34,7 +43,6 @@ CONTROLNET_DEFAULT_MODELS = [ "lllyasviel/sd-controlnet-scribble", "lllyasviel/sd-controlnet-normal", "lllyasviel/sd-controlnet-mlsd", - ############################################# # lllyasviel sd v1.5, ControlNet v1.1 models ############################################# @@ -56,7 +64,6 @@ CONTROLNET_DEFAULT_MODELS = [ "lllyasviel/control_v11e_sd15_shuffle", "lllyasviel/control_v11e_sd15_ip2p", "lllyasviel/control_v11f1e_sd15_tile", - ################################################# # thibaud sd v2.1 models (ControlNet v1.0? or v1.1? ################################################## @@ -71,7 +78,6 @@ CONTROLNET_DEFAULT_MODELS = [ "thibaud/controlnet-sd21-lineart-diffusers", "thibaud/controlnet-sd21-normalbae-diffusers", "thibaud/controlnet-sd21-ade20k-diffusers", - ############################################## # ControlNetMediaPipeface, ControlNet v1.1 ############################################## @@ -83,10 +89,17 @@ CONTROLNET_DEFAULT_MODELS = [ ] CONTROLNET_NAME_VALUES = Literal[tuple(CONTROLNET_DEFAULT_MODELS)] -CONTROLNET_MODE_VALUES = Literal[tuple( - ["balanced", "more_prompt", "more_control", "unbalanced"])] -CONTROLNET_RESIZE_VALUES = Literal[tuple( - ["just_resize", "crop_resize", "fill_resize", "just_resize_simple",])] +CONTROLNET_MODE_VALUES = Literal[tuple(["balanced", "more_prompt", "more_control", "unbalanced"])] +CONTROLNET_RESIZE_VALUES = Literal[ + tuple( + [ + "just_resize", + "crop_resize", + "fill_resize", + "just_resize_simple", + ] + ) +] class ControlNetModelField(BaseModel): @@ -98,21 +111,17 @@ class ControlNetModelField(BaseModel): class ControlField(BaseModel): image: ImageField = Field(default=None, description="The control image") - control_model: Optional[ControlNetModelField] = Field( - default=None, description="The ControlNet model to use") + control_model: Optional[ControlNetModelField] = Field(default=None, description="The ControlNet model to use") # control_weight: Optional[float] = Field(default=1, description="weight given to controlnet") - control_weight: Union[float, List[float]] = Field( - default=1, description="The weight given to the ControlNet") + control_weight: Union[float, List[float]] = Field(default=1, description="The weight given to the ControlNet") begin_step_percent: float = Field( - default=0, ge=0, le=1, - description="When the ControlNet is first applied (% of total steps)") + default=0, ge=0, le=1, description="When the ControlNet is first applied (% of total steps)" + ) end_step_percent: float = Field( - default=1, ge=0, le=1, - description="When the ControlNet is last applied (% of total steps)") - control_mode: CONTROLNET_MODE_VALUES = Field( - default="balanced", description="The control mode to use") - resize_mode: CONTROLNET_RESIZE_VALUES = Field( - default="just_resize", description="The resize mode to use") + default=1, ge=0, le=1, description="When the ControlNet is last applied (% of total steps)" + ) + control_mode: CONTROLNET_MODE_VALUES = Field(default="balanced", description="The control mode to use") + resize_mode: CONTROLNET_RESIZE_VALUES = Field(default="just_resize", description="The resize mode to use") @validator("control_weight") def validate_control_weight(cls, v): @@ -120,11 +129,10 @@ class ControlField(BaseModel): if isinstance(v, list): for i in v: if i < -1 or i > 2: - raise ValueError( - 'Control weights must be within -1 to 2 range') + raise ValueError("Control weights must be within -1 to 2 range") else: if v < -1 or v > 2: - raise ValueError('Control weights must be within -1 to 2 range') + raise ValueError("Control weights must be within -1 to 2 range") return v class Config: @@ -136,12 +144,13 @@ class ControlField(BaseModel): "control_model": "controlnet_model", # "control_weight": "number", } - } + }, } class ControlOutput(BaseInvocationOutput): """node output for ControlNet info""" + # fmt: off type: Literal["control_output"] = "control_output" control: ControlField = Field(default=None, description="The control info") @@ -150,6 +159,7 @@ class ControlOutput(BaseInvocationOutput): class ControlNetInvocation(BaseInvocation): """Collects ControlNet info to pass to other nodes""" + # fmt: off type: Literal["controlnet"] = "controlnet" # Inputs @@ -176,7 +186,7 @@ class ControlNetInvocation(BaseInvocation): # "cfg_scale": "float", "cfg_scale": "number", "control_weight": "float", - } + }, }, } @@ -205,10 +215,7 @@ class ImageProcessorInvocation(BaseInvocation, PILInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Image Processor", - "tags": ["image", "processor"] - }, + "ui": {"title": "Image Processor", "tags": ["image", "processor"]}, } def run_processor(self, image): @@ -233,7 +240,7 @@ class ImageProcessorInvocation(BaseInvocation, PILInvocationConfig): image_category=ImageCategory.CONTROL, session_id=context.graph_execution_state_id, node_id=self.id, - is_intermediate=self.is_intermediate + is_intermediate=self.is_intermediate, ) """Builds an ImageOutput and its ImageField""" @@ -248,9 +255,9 @@ class ImageProcessorInvocation(BaseInvocation, PILInvocationConfig): ) -class CannyImageProcessorInvocation( - ImageProcessorInvocation, PILInvocationConfig): +class CannyImageProcessorInvocation(ImageProcessorInvocation, PILInvocationConfig): """Canny edge detection for ControlNet""" + # fmt: off type: Literal["canny_image_processor"] = "canny_image_processor" # Input @@ -260,22 +267,18 @@ class CannyImageProcessorInvocation( class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Canny Processor", - "tags": ["controlnet", "canny", "image", "processor"] - }, + "ui": {"title": "Canny Processor", "tags": ["controlnet", "canny", "image", "processor"]}, } def run_processor(self, image): canny_processor = CannyDetector() - processed_image = canny_processor( - image, self.low_threshold, self.high_threshold) + processed_image = canny_processor(image, self.low_threshold, self.high_threshold) return processed_image -class HedImageProcessorInvocation( - ImageProcessorInvocation, PILInvocationConfig): +class HedImageProcessorInvocation(ImageProcessorInvocation, PILInvocationConfig): """Applies HED edge detection to image""" + # fmt: off type: Literal["hed_image_processor"] = "hed_image_processor" # Inputs @@ -288,27 +291,25 @@ class HedImageProcessorInvocation( class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Softedge(HED) Processor", - "tags": ["controlnet", "softedge", "hed", "image", "processor"] - }, + "ui": {"title": "Softedge(HED) Processor", "tags": ["controlnet", "softedge", "hed", "image", "processor"]}, } def run_processor(self, image): hed_processor = HEDdetector.from_pretrained("lllyasviel/Annotators") - processed_image = hed_processor(image, - detect_resolution=self.detect_resolution, - image_resolution=self.image_resolution, - # safe not supported in controlnet_aux v0.0.3 - # safe=self.safe, - scribble=self.scribble, - ) + processed_image = hed_processor( + image, + detect_resolution=self.detect_resolution, + image_resolution=self.image_resolution, + # safe not supported in controlnet_aux v0.0.3 + # safe=self.safe, + scribble=self.scribble, + ) return processed_image -class LineartImageProcessorInvocation( - ImageProcessorInvocation, PILInvocationConfig): +class LineartImageProcessorInvocation(ImageProcessorInvocation, PILInvocationConfig): """Applies line art processing to image""" + # fmt: off type: Literal["lineart_image_processor"] = "lineart_image_processor" # Inputs @@ -319,24 +320,20 @@ class LineartImageProcessorInvocation( class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Lineart Processor", - "tags": ["controlnet", "lineart", "image", "processor"] - }, + "ui": {"title": "Lineart Processor", "tags": ["controlnet", "lineart", "image", "processor"]}, } def run_processor(self, image): - lineart_processor = LineartDetector.from_pretrained( - "lllyasviel/Annotators") + lineart_processor = LineartDetector.from_pretrained("lllyasviel/Annotators") processed_image = lineart_processor( - image, detect_resolution=self.detect_resolution, - image_resolution=self.image_resolution, coarse=self.coarse) + image, detect_resolution=self.detect_resolution, image_resolution=self.image_resolution, coarse=self.coarse + ) return processed_image -class LineartAnimeImageProcessorInvocation( - ImageProcessorInvocation, PILInvocationConfig): +class LineartAnimeImageProcessorInvocation(ImageProcessorInvocation, PILInvocationConfig): """Applies line art anime processing to image""" + # fmt: off type: Literal["lineart_anime_image_processor"] = "lineart_anime_image_processor" # Inputs @@ -348,23 +345,23 @@ class LineartAnimeImageProcessorInvocation( schema_extra = { "ui": { "title": "Lineart Anime Processor", - "tags": ["controlnet", "lineart", "anime", "image", "processor"] + "tags": ["controlnet", "lineart", "anime", "image", "processor"], }, } def run_processor(self, image): - processor = LineartAnimeDetector.from_pretrained( - "lllyasviel/Annotators") - processed_image = processor(image, - detect_resolution=self.detect_resolution, - image_resolution=self.image_resolution, - ) + processor = LineartAnimeDetector.from_pretrained("lllyasviel/Annotators") + processed_image = processor( + image, + detect_resolution=self.detect_resolution, + image_resolution=self.image_resolution, + ) return processed_image -class OpenposeImageProcessorInvocation( - ImageProcessorInvocation, PILInvocationConfig): +class OpenposeImageProcessorInvocation(ImageProcessorInvocation, PILInvocationConfig): """Applies Openpose processing to image""" + # fmt: off type: Literal["openpose_image_processor"] = "openpose_image_processor" # Inputs @@ -375,25 +372,23 @@ class OpenposeImageProcessorInvocation( class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Openpose Processor", - "tags": ["controlnet", "openpose", "image", "processor"] - }, + "ui": {"title": "Openpose Processor", "tags": ["controlnet", "openpose", "image", "processor"]}, } def run_processor(self, image): - openpose_processor = OpenposeDetector.from_pretrained( - "lllyasviel/Annotators") + openpose_processor = OpenposeDetector.from_pretrained("lllyasviel/Annotators") processed_image = openpose_processor( - image, detect_resolution=self.detect_resolution, + image, + detect_resolution=self.detect_resolution, image_resolution=self.image_resolution, - hand_and_face=self.hand_and_face,) + hand_and_face=self.hand_and_face, + ) return processed_image -class MidasDepthImageProcessorInvocation( - ImageProcessorInvocation, PILInvocationConfig): +class MidasDepthImageProcessorInvocation(ImageProcessorInvocation, PILInvocationConfig): """Applies Midas depth processing to image""" + # fmt: off type: Literal["midas_depth_image_processor"] = "midas_depth_image_processor" # Inputs @@ -405,26 +400,24 @@ class MidasDepthImageProcessorInvocation( class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Midas (Depth) Processor", - "tags": ["controlnet", "midas", "depth", "image", "processor"] - }, + "ui": {"title": "Midas (Depth) Processor", "tags": ["controlnet", "midas", "depth", "image", "processor"]}, } def run_processor(self, image): midas_processor = MidasDetector.from_pretrained("lllyasviel/Annotators") - processed_image = midas_processor(image, - a=np.pi * self.a_mult, - bg_th=self.bg_th, - # dept_and_normal not supported in controlnet_aux v0.0.3 - # depth_and_normal=self.depth_and_normal, - ) + processed_image = midas_processor( + image, + a=np.pi * self.a_mult, + bg_th=self.bg_th, + # dept_and_normal not supported in controlnet_aux v0.0.3 + # depth_and_normal=self.depth_and_normal, + ) return processed_image -class NormalbaeImageProcessorInvocation( - ImageProcessorInvocation, PILInvocationConfig): +class NormalbaeImageProcessorInvocation(ImageProcessorInvocation, PILInvocationConfig): """Applies NormalBae processing to image""" + # fmt: off type: Literal["normalbae_image_processor"] = "normalbae_image_processor" # Inputs @@ -434,24 +427,20 @@ class NormalbaeImageProcessorInvocation( class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Normal BAE Processor", - "tags": ["controlnet", "normal", "bae", "image", "processor"] - }, + "ui": {"title": "Normal BAE Processor", "tags": ["controlnet", "normal", "bae", "image", "processor"]}, } def run_processor(self, image): - normalbae_processor = NormalBaeDetector.from_pretrained( - "lllyasviel/Annotators") + normalbae_processor = NormalBaeDetector.from_pretrained("lllyasviel/Annotators") processed_image = normalbae_processor( - image, detect_resolution=self.detect_resolution, - image_resolution=self.image_resolution) + image, detect_resolution=self.detect_resolution, image_resolution=self.image_resolution + ) return processed_image -class MlsdImageProcessorInvocation( - ImageProcessorInvocation, PILInvocationConfig): +class MlsdImageProcessorInvocation(ImageProcessorInvocation, PILInvocationConfig): """Applies MLSD processing to image""" + # fmt: off type: Literal["mlsd_image_processor"] = "mlsd_image_processor" # Inputs @@ -463,24 +452,24 @@ class MlsdImageProcessorInvocation( class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "MLSD Processor", - "tags": ["controlnet", "mlsd", "image", "processor"] - }, + "ui": {"title": "MLSD Processor", "tags": ["controlnet", "mlsd", "image", "processor"]}, } def run_processor(self, image): mlsd_processor = MLSDdetector.from_pretrained("lllyasviel/Annotators") processed_image = mlsd_processor( - image, detect_resolution=self.detect_resolution, - image_resolution=self.image_resolution, thr_v=self.thr_v, - thr_d=self.thr_d) + image, + detect_resolution=self.detect_resolution, + image_resolution=self.image_resolution, + thr_v=self.thr_v, + thr_d=self.thr_d, + ) return processed_image -class PidiImageProcessorInvocation( - ImageProcessorInvocation, PILInvocationConfig): +class PidiImageProcessorInvocation(ImageProcessorInvocation, PILInvocationConfig): """Applies PIDI processing to image""" + # fmt: off type: Literal["pidi_image_processor"] = "pidi_image_processor" # Inputs @@ -492,25 +481,24 @@ class PidiImageProcessorInvocation( class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "PIDI Processor", - "tags": ["controlnet", "pidi", "image", "processor"] - }, + "ui": {"title": "PIDI Processor", "tags": ["controlnet", "pidi", "image", "processor"]}, } def run_processor(self, image): - pidi_processor = PidiNetDetector.from_pretrained( - "lllyasviel/Annotators") + pidi_processor = PidiNetDetector.from_pretrained("lllyasviel/Annotators") processed_image = pidi_processor( - image, detect_resolution=self.detect_resolution, - image_resolution=self.image_resolution, safe=self.safe, - scribble=self.scribble) + image, + detect_resolution=self.detect_resolution, + image_resolution=self.image_resolution, + safe=self.safe, + scribble=self.scribble, + ) return processed_image -class ContentShuffleImageProcessorInvocation( - ImageProcessorInvocation, PILInvocationConfig): +class ContentShuffleImageProcessorInvocation(ImageProcessorInvocation, PILInvocationConfig): """Applies content shuffle processing to image""" + # fmt: off type: Literal["content_shuffle_image_processor"] = "content_shuffle_image_processor" # Inputs @@ -525,48 +513,45 @@ class ContentShuffleImageProcessorInvocation( schema_extra = { "ui": { "title": "Content Shuffle Processor", - "tags": ["controlnet", "contentshuffle", "image", "processor"] + "tags": ["controlnet", "contentshuffle", "image", "processor"], }, } def run_processor(self, image): content_shuffle_processor = ContentShuffleDetector() - processed_image = content_shuffle_processor(image, - detect_resolution=self.detect_resolution, - image_resolution=self.image_resolution, - h=self.h, - w=self.w, - f=self.f - ) + processed_image = content_shuffle_processor( + image, + detect_resolution=self.detect_resolution, + image_resolution=self.image_resolution, + h=self.h, + w=self.w, + f=self.f, + ) return processed_image # should work with controlnet_aux >= 0.0.4 and timm <= 0.6.13 -class ZoeDepthImageProcessorInvocation( - ImageProcessorInvocation, PILInvocationConfig): +class ZoeDepthImageProcessorInvocation(ImageProcessorInvocation, PILInvocationConfig): """Applies Zoe depth processing to image""" + # fmt: off type: Literal["zoe_depth_image_processor"] = "zoe_depth_image_processor" # fmt: on class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Zoe (Depth) Processor", - "tags": ["controlnet", "zoe", "depth", "image", "processor"] - }, + "ui": {"title": "Zoe (Depth) Processor", "tags": ["controlnet", "zoe", "depth", "image", "processor"]}, } def run_processor(self, image): - zoe_depth_processor = ZoeDetector.from_pretrained( - "lllyasviel/Annotators") + zoe_depth_processor = ZoeDetector.from_pretrained("lllyasviel/Annotators") processed_image = zoe_depth_processor(image) return processed_image -class MediapipeFaceProcessorInvocation( - ImageProcessorInvocation, PILInvocationConfig): +class MediapipeFaceProcessorInvocation(ImageProcessorInvocation, PILInvocationConfig): """Applies mediapipe face processing to image""" + # fmt: off type: Literal["mediapipe_face_processor"] = "mediapipe_face_processor" # Inputs @@ -576,26 +561,22 @@ class MediapipeFaceProcessorInvocation( class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Mediapipe Processor", - "tags": ["controlnet", "mediapipe", "image", "processor"] - }, + "ui": {"title": "Mediapipe Processor", "tags": ["controlnet", "mediapipe", "image", "processor"]}, } def run_processor(self, image): # MediaPipeFaceDetector throws an error if image has alpha channel # so convert to RGB if needed - if image.mode == 'RGBA': - image = image.convert('RGB') + if image.mode == "RGBA": + image = image.convert("RGB") mediapipe_face_processor = MediapipeFaceDetector() - processed_image = mediapipe_face_processor( - image, max_faces=self.max_faces, min_confidence=self.min_confidence) + processed_image = mediapipe_face_processor(image, max_faces=self.max_faces, min_confidence=self.min_confidence) return processed_image -class LeresImageProcessorInvocation( - ImageProcessorInvocation, PILInvocationConfig): +class LeresImageProcessorInvocation(ImageProcessorInvocation, PILInvocationConfig): """Applies leres processing to image""" + # fmt: off type: Literal["leres_image_processor"] = "leres_image_processor" # Inputs @@ -608,24 +589,23 @@ class LeresImageProcessorInvocation( class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Leres (Depth) Processor", - "tags": ["controlnet", "leres", "depth", "image", "processor"] - }, + "ui": {"title": "Leres (Depth) Processor", "tags": ["controlnet", "leres", "depth", "image", "processor"]}, } def run_processor(self, image): leres_processor = LeresDetector.from_pretrained("lllyasviel/Annotators") processed_image = leres_processor( - image, thr_a=self.thr_a, thr_b=self.thr_b, boost=self.boost, + image, + thr_a=self.thr_a, + thr_b=self.thr_b, + boost=self.boost, detect_resolution=self.detect_resolution, - image_resolution=self.image_resolution) + image_resolution=self.image_resolution, + ) return processed_image -class TileResamplerProcessorInvocation( - ImageProcessorInvocation, PILInvocationConfig): - +class TileResamplerProcessorInvocation(ImageProcessorInvocation, PILInvocationConfig): # fmt: off type: Literal["tile_image_processor"] = "tile_image_processor" # Inputs @@ -637,16 +617,17 @@ class TileResamplerProcessorInvocation( schema_extra = { "ui": { "title": "Tile Resample Processor", - "tags": ["controlnet", "tile", "resample", "image", "processor"] + "tags": ["controlnet", "tile", "resample", "image", "processor"], }, } # tile_resample copied from sd-webui-controlnet/scripts/processor.py - def tile_resample(self, - np_img: np.ndarray, - res=512, # never used? - down_sampling_rate=1.0, - ): + def tile_resample( + self, + np_img: np.ndarray, + res=512, # never used? + down_sampling_rate=1.0, + ): np_img = HWC3(np_img) if down_sampling_rate < 1.1: return np_img @@ -658,36 +639,41 @@ class TileResamplerProcessorInvocation( def run_processor(self, img): np_img = np.array(img, dtype=np.uint8) - processed_np_image = self.tile_resample(np_img, - # res=self.tile_size, - down_sampling_rate=self.down_sampling_rate - ) + processed_np_image = self.tile_resample( + np_img, + # res=self.tile_size, + down_sampling_rate=self.down_sampling_rate, + ) processed_image = Image.fromarray(processed_np_image) return processed_image -class SegmentAnythingProcessorInvocation( - ImageProcessorInvocation, PILInvocationConfig): +class SegmentAnythingProcessorInvocation(ImageProcessorInvocation, PILInvocationConfig): """Applies segment anything processing to image""" + # fmt: off type: Literal["segment_anything_processor"] = "segment_anything_processor" # fmt: on class Config(InvocationConfig): - schema_extra = {"ui": {"title": "Segment Anything Processor", "tags": [ - "controlnet", "segment", "anything", "sam", "image", "processor"]}, } + schema_extra = { + "ui": { + "title": "Segment Anything Processor", + "tags": ["controlnet", "segment", "anything", "sam", "image", "processor"], + }, + } def run_processor(self, image): # segment_anything_processor = SamDetector.from_pretrained("ybelkada/segment-anything", subfolder="checkpoints") segment_anything_processor = SamDetectorReproducibleColors.from_pretrained( - "ybelkada/segment-anything", subfolder="checkpoints") + "ybelkada/segment-anything", subfolder="checkpoints" + ) np_img = np.array(image, dtype=np.uint8) processed_image = segment_anything_processor(np_img) return processed_image class SamDetectorReproducibleColors(SamDetector): - # overriding SamDetector.show_anns() method to use reproducible colors for segmentation image # base class show_anns() method randomizes colors, # which seems to also lead to non-reproducible image generation @@ -695,19 +681,15 @@ class SamDetectorReproducibleColors(SamDetector): def show_anns(self, anns: List[Dict]): if len(anns) == 0: return - sorted_anns = sorted(anns, key=(lambda x: x['area']), reverse=True) - h, w = anns[0]['segmentation'].shape - final_img = Image.fromarray( - np.zeros((h, w, 3), dtype=np.uint8), mode="RGB") + sorted_anns = sorted(anns, key=(lambda x: x["area"]), reverse=True) + h, w = anns[0]["segmentation"].shape + final_img = Image.fromarray(np.zeros((h, w, 3), dtype=np.uint8), mode="RGB") palette = ade_palette() for i, ann in enumerate(sorted_anns): - m = ann['segmentation'] + m = ann["segmentation"] img = np.empty((m.shape[0], m.shape[1], 3), dtype=np.uint8) # doing modulo just in case number of annotated regions exceeds number of colors in palette ann_color = palette[i % len(palette)] img[:, :] = ann_color - final_img.paste( - Image.fromarray(img, mode="RGB"), - (0, 0), - Image.fromarray(np.uint8(m * 255))) + final_img.paste(Image.fromarray(img, mode="RGB"), (0, 0), Image.fromarray(np.uint8(m * 255))) return np.array(final_img, dtype=np.uint8) diff --git a/invokeai/app/invocations/cv.py b/invokeai/app/invocations/cv.py index cd7eaebeec..bd3a4adbe4 100644 --- a/invokeai/app/invocations/cv.py +++ b/invokeai/app/invocations/cv.py @@ -37,10 +37,7 @@ class CvInpaintInvocation(BaseInvocation, CvInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "OpenCV Inpaint", - "tags": ["opencv", "inpaint"] - }, + "ui": {"title": "OpenCV Inpaint", "tags": ["opencv", "inpaint"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: diff --git a/invokeai/app/invocations/generate.py b/invokeai/app/invocations/generate.py index 910a7edf8b..d48c9f922e 100644 --- a/invokeai/app/invocations/generate.py +++ b/invokeai/app/invocations/generate.py @@ -6,8 +6,7 @@ from typing import Literal, Optional, get_args import torch from pydantic import Field -from invokeai.app.models.image import (ColorField, ImageCategory, ImageField, - ResourceOrigin) +from invokeai.app.models.image import ColorField, ImageCategory, ImageField, ResourceOrigin from invokeai.app.util.misc import SEED_MAX, get_random_seed from invokeai.backend.generator.inpaint import infill_methods @@ -25,13 +24,12 @@ from contextlib import contextmanager, ExitStack, ContextDecorator SAMPLER_NAME_VALUES = Literal[tuple(InvokeAIGenerator.schedulers())] INFILL_METHODS = Literal[tuple(infill_methods())] -DEFAULT_INFILL_METHOD = ( - "patchmatch" if "patchmatch" in get_args(INFILL_METHODS) else "tile" -) +DEFAULT_INFILL_METHOD = "patchmatch" if "patchmatch" in get_args(INFILL_METHODS) else "tile" from .latent import get_scheduler + class OldModelContext(ContextDecorator): model: StableDiffusionGeneratorPipeline @@ -44,6 +42,7 @@ class OldModelContext(ContextDecorator): def __exit__(self, *exc): return False + class OldModelInfo: name: str hash: str @@ -64,20 +63,34 @@ class InpaintInvocation(BaseInvocation): positive_conditioning: Optional[ConditioningField] = Field(description="Positive conditioning for generation") negative_conditioning: Optional[ConditioningField] = Field(description="Negative conditioning for generation") - seed: int = Field(ge=0, le=SEED_MAX, description="The seed to use (omit for random)", default_factory=get_random_seed) - steps: int = Field(default=30, gt=0, description="The number of steps to use to generate the image") - width: int = Field(default=512, multiple_of=8, gt=0, description="The width of the resulting image", ) - height: int = Field(default=512, multiple_of=8, gt=0, description="The height of the resulting image", ) - cfg_scale: float = Field(default=7.5, ge=1, description="The Classifier-Free Guidance, higher values may result in a result closer to the prompt", ) - scheduler: SAMPLER_NAME_VALUES = Field(default="euler", description="The scheduler to use" ) + seed: int = Field( + ge=0, le=SEED_MAX, description="The seed to use (omit for random)", default_factory=get_random_seed + ) + steps: int = Field(default=30, gt=0, description="The number of steps to use to generate the image") + width: int = Field( + default=512, + multiple_of=8, + gt=0, + description="The width of the resulting image", + ) + height: int = Field( + default=512, + multiple_of=8, + gt=0, + description="The height of the resulting image", + ) + cfg_scale: float = Field( + default=7.5, + ge=1, + description="The Classifier-Free Guidance, higher values may result in a result closer to the prompt", + ) + scheduler: SAMPLER_NAME_VALUES = Field(default="euler", description="The scheduler to use") unet: UNetField = Field(default=None, description="UNet model") vae: VaeField = Field(default=None, description="Vae model") # Inputs image: Optional[ImageField] = Field(description="The input image") - strength: float = Field( - default=0.75, gt=0, le=1, description="The strength of the original image" - ) + strength: float = Field(default=0.75, gt=0, le=1, description="The strength of the original image") fit: bool = Field( default=True, description="Whether or not the result should be fit to the aspect ratio of the input image", @@ -86,18 +99,10 @@ class InpaintInvocation(BaseInvocation): # Inputs mask: Optional[ImageField] = Field(description="The mask") seam_size: int = Field(default=96, ge=1, description="The seam inpaint size (px)") - seam_blur: int = Field( - default=16, ge=0, description="The seam inpaint blur radius (px)" - ) - seam_strength: float = Field( - default=0.75, gt=0, le=1, description="The seam inpaint strength" - ) - seam_steps: int = Field( - default=30, ge=1, description="The number of steps to use for seam inpaint" - ) - tile_size: int = Field( - default=32, ge=1, description="The tile infill method size (px)" - ) + seam_blur: int = Field(default=16, ge=0, description="The seam inpaint blur radius (px)") + seam_strength: float = Field(default=0.75, gt=0, le=1, description="The seam inpaint strength") + seam_steps: int = Field(default=30, ge=1, description="The number of steps to use for seam inpaint") + tile_size: int = Field(default=32, ge=1, description="The tile infill method size (px)") infill_method: INFILL_METHODS = Field( default=DEFAULT_INFILL_METHOD, description="The method used to infill empty regions (px)", @@ -128,10 +133,7 @@ class InpaintInvocation(BaseInvocation): # Schema customisation class Config(InvocationConfig): schema_extra = { - "ui": { - "tags": ["stable-diffusion", "image"], - "title": "Inpaint" - }, + "ui": {"tags": ["stable-diffusion", "image"], "title": "Inpaint"}, } def dispatch_progress( @@ -162,18 +164,23 @@ class InpaintInvocation(BaseInvocation): def _lora_loader(): for lora in self.unet.loras: lora_info = context.services.model_manager.get_model( - **lora.dict(exclude={"weight"}), context=context,) + **lora.dict(exclude={"weight"}), + context=context, + ) yield (lora_info.context.model, lora.weight) del lora_info return - - unet_info = context.services.model_manager.get_model(**self.unet.unet.dict(), context=context,) - vae_info = context.services.model_manager.get_model(**self.vae.vae.dict(), context=context,) - with vae_info as vae,\ - ModelPatcher.apply_lora_unet(unet_info.context.model, _lora_loader()),\ - unet_info as unet: + unet_info = context.services.model_manager.get_model( + **self.unet.unet.dict(), + context=context, + ) + vae_info = context.services.model_manager.get_model( + **self.vae.vae.dict(), + context=context, + ) + with vae_info as vae, ModelPatcher.apply_lora_unet(unet_info.context.model, _lora_loader()), unet_info as unet: device = context.services.model_manager.mgr.cache.execution_device dtype = context.services.model_manager.mgr.cache.precision @@ -197,21 +204,11 @@ class InpaintInvocation(BaseInvocation): ) def invoke(self, context: InvocationContext) -> ImageOutput: - image = ( - None - if self.image is None - else context.services.images.get_pil_image(self.image.image_name) - ) - mask = ( - None - if self.mask is None - else context.services.images.get_pil_image(self.mask.image_name) - ) + image = None if self.image is None else context.services.images.get_pil_image(self.image.image_name) + mask = None if self.mask is None else context.services.images.get_pil_image(self.mask.image_name) # Get the source node id (we are invoking the prepared node) - graph_execution_state = context.services.graph_execution_manager.get( - context.graph_execution_state_id - ) + graph_execution_state = context.services.graph_execution_manager.get(context.graph_execution_state_id) source_node_id = graph_execution_state.prepared_source_mapping[self.id] scheduler = get_scheduler( diff --git a/invokeai/app/invocations/image.py b/invokeai/app/invocations/image.py index 26ee9e391d..3f40ea3cbe 100644 --- a/invokeai/app/invocations/image.py +++ b/invokeai/app/invocations/image.py @@ -9,9 +9,13 @@ from pathlib import Path from typing import Union from invokeai.app.invocations.metadata import CoreMetadata from ..models.image import ( - ImageCategory, ImageField, ResourceOrigin, - PILInvocationConfig, ImageOutput, MaskOutput, -) + ImageCategory, + ImageField, + ResourceOrigin, + PILInvocationConfig, + ImageOutput, + MaskOutput, +) from .baseinvocation import ( BaseInvocation, InvocationContext, @@ -20,6 +24,7 @@ from .baseinvocation import ( from invokeai.backend.image_util.safety_checker import SafetyChecker from invokeai.backend.image_util.invisible_watermark import InvisibleWatermark + class LoadImageInvocation(BaseInvocation): """Load an image and provide it as output.""" @@ -34,10 +39,7 @@ class LoadImageInvocation(BaseInvocation): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Load Image", - "tags": ["image", "load"] - }, + "ui": {"title": "Load Image", "tags": ["image", "load"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: @@ -56,16 +58,11 @@ class ShowImageInvocation(BaseInvocation): type: Literal["show_image"] = "show_image" # Inputs - image: Optional[ImageField] = Field( - default=None, description="The image to show" - ) + image: Optional[ImageField] = Field(default=None, description="The image to show") class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Show Image", - "tags": ["image", "show"] - }, + "ui": {"title": "Show Image", "tags": ["image", "show"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: @@ -98,18 +95,13 @@ class ImageCropInvocation(BaseInvocation, PILInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Crop Image", - "tags": ["image", "crop"] - }, + "ui": {"title": "Crop Image", "tags": ["image", "crop"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: image = context.services.images.get_pil_image(self.image.image_name) - image_crop = Image.new( - mode="RGBA", size=(self.width, self.height), color=(0, 0, 0, 0) - ) + image_crop = Image.new(mode="RGBA", size=(self.width, self.height), color=(0, 0, 0, 0)) image_crop.paste(image, (-self.x, -self.y)) image_dto = context.services.images.create( @@ -144,21 +136,14 @@ class ImagePasteInvocation(BaseInvocation, PILInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Paste Image", - "tags": ["image", "paste"] - }, + "ui": {"title": "Paste Image", "tags": ["image", "paste"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: base_image = context.services.images.get_pil_image(self.base_image.image_name) image = context.services.images.get_pil_image(self.image.image_name) mask = ( - None - if self.mask is None - else ImageOps.invert( - context.services.images.get_pil_image(self.mask.image_name) - ) + None if self.mask is None else ImageOps.invert(context.services.images.get_pil_image(self.mask.image_name)) ) # TODO: probably shouldn't invert mask here... should user be required to do it? @@ -167,9 +152,7 @@ class ImagePasteInvocation(BaseInvocation, PILInvocationConfig): max_x = max(base_image.width, image.width + self.x) max_y = max(base_image.height, image.height + self.y) - new_image = Image.new( - mode="RGBA", size=(max_x - min_x, max_y - min_y), color=(0, 0, 0, 0) - ) + new_image = Image.new(mode="RGBA", size=(max_x - min_x, max_y - min_y), color=(0, 0, 0, 0)) new_image.paste(base_image, (abs(min_x), abs(min_y))) new_image.paste(image, (max(0, self.x), max(0, self.y)), mask=mask) @@ -202,10 +185,7 @@ class MaskFromAlphaInvocation(BaseInvocation, PILInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Mask From Alpha", - "tags": ["image", "mask", "alpha"] - }, + "ui": {"title": "Mask From Alpha", "tags": ["image", "mask", "alpha"]}, } def invoke(self, context: InvocationContext) -> MaskOutput: @@ -244,10 +224,7 @@ class ImageMultiplyInvocation(BaseInvocation, PILInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Multiply Images", - "tags": ["image", "multiply"] - }, + "ui": {"title": "Multiply Images", "tags": ["image", "multiply"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: @@ -288,10 +265,7 @@ class ImageChannelInvocation(BaseInvocation, PILInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Image Channel", - "tags": ["image", "channel"] - }, + "ui": {"title": "Image Channel", "tags": ["image", "channel"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: @@ -331,10 +305,7 @@ class ImageConvertInvocation(BaseInvocation, PILInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Convert Image", - "tags": ["image", "convert"] - }, + "ui": {"title": "Convert Image", "tags": ["image", "convert"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: @@ -357,6 +328,7 @@ class ImageConvertInvocation(BaseInvocation, PILInvocationConfig): height=image_dto.height, ) + class ImageBlurInvocation(BaseInvocation, PILInvocationConfig): """Blurs an image""" @@ -371,19 +343,14 @@ class ImageBlurInvocation(BaseInvocation, PILInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Blur Image", - "tags": ["image", "blur"] - }, + "ui": {"title": "Blur Image", "tags": ["image", "blur"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: image = context.services.images.get_pil_image(self.image.image_name) blur = ( - ImageFilter.GaussianBlur(self.radius) - if self.blur_type == "gaussian" - else ImageFilter.BoxBlur(self.radius) + ImageFilter.GaussianBlur(self.radius) if self.blur_type == "gaussian" else ImageFilter.BoxBlur(self.radius) ) blur_image = image.filter(blur) @@ -438,10 +405,7 @@ class ImageResizeInvocation(BaseInvocation, PILInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Resize Image", - "tags": ["image", "resize"] - }, + "ui": {"title": "Resize Image", "tags": ["image", "resize"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: @@ -484,10 +448,7 @@ class ImageScaleInvocation(BaseInvocation, PILInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Scale Image", - "tags": ["image", "scale"] - }, + "ui": {"title": "Scale Image", "tags": ["image", "scale"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: @@ -532,10 +493,7 @@ class ImageLerpInvocation(BaseInvocation, PILInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Image Linear Interpolation", - "tags": ["image", "linear", "interpolation", "lerp"] - }, + "ui": {"title": "Image Linear Interpolation", "tags": ["image", "linear", "interpolation", "lerp"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: @@ -561,6 +519,7 @@ class ImageLerpInvocation(BaseInvocation, PILInvocationConfig): height=image_dto.height, ) + class ImageInverseLerpInvocation(BaseInvocation, PILInvocationConfig): """Inverse linear interpolation of all pixels of an image""" @@ -577,7 +536,7 @@ class ImageInverseLerpInvocation(BaseInvocation, PILInvocationConfig): schema_extra = { "ui": { "title": "Image Inverse Linear Interpolation", - "tags": ["image", "linear", "interpolation", "inverse"] + "tags": ["image", "linear", "interpolation", "inverse"], }, } @@ -585,12 +544,7 @@ class ImageInverseLerpInvocation(BaseInvocation, PILInvocationConfig): image = context.services.images.get_pil_image(self.image.image_name) image_arr = numpy.asarray(image, dtype=numpy.float32) - image_arr = ( - numpy.minimum( - numpy.maximum(image_arr - self.min, 0) / float(self.max - self.min), 1 - ) - * 255 - ) + image_arr = numpy.minimum(numpy.maximum(image_arr - self.min, 0) / float(self.max - self.min), 1) * 255 ilerp_image = Image.fromarray(numpy.uint8(image_arr)) @@ -609,6 +563,7 @@ class ImageInverseLerpInvocation(BaseInvocation, PILInvocationConfig): height=image_dto.height, ) + class ImageNSFWBlurInvocation(BaseInvocation, PILInvocationConfig): """Add blur to NSFW-flagged images""" @@ -622,22 +577,19 @@ class ImageNSFWBlurInvocation(BaseInvocation, PILInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Blur NSFW Images", - "tags": ["image", "nsfw", "checker"] - }, + "ui": {"title": "Blur NSFW Images", "tags": ["image", "nsfw", "checker"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: image = context.services.images.get_pil_image(self.image.image_name) - + logger = context.services.logger logger.debug("Running NSFW checker") if SafetyChecker.has_nsfw_concept(image): logger.info("A potentially NSFW image has been detected. Image will be blurred.") blurry_image = image.filter(filter=ImageFilter.GaussianBlur(radius=32)) caution = self._get_caution_img() - blurry_image.paste(caution,(0,0),caution) + blurry_image.paste(caution, (0, 0), caution) image = blurry_image image_dto = context.services.images.create( @@ -649,20 +601,22 @@ class ImageNSFWBlurInvocation(BaseInvocation, PILInvocationConfig): is_intermediate=self.is_intermediate, metadata=self.metadata.dict() if self.metadata else None, ) - + return ImageOutput( image=ImageField(image_name=image_dto.image_name), width=image_dto.width, height=image_dto.height, ) - - def _get_caution_img(self)->Image: + + def _get_caution_img(self) -> Image: import invokeai.app.assets.images as image_assets - caution = Image.open(Path(image_assets.__path__[0]) / 'caution.png') - return caution.resize((caution.width // 2, caution.height //2)) + + caution = Image.open(Path(image_assets.__path__[0]) / "caution.png") + return caution.resize((caution.width // 2, caution.height // 2)) + class ImageWatermarkInvocation(BaseInvocation, PILInvocationConfig): - """ Add an invisible watermark to an image """ + """Add an invisible watermark to an image""" # fmt: off type: Literal["img_watermark"] = "img_watermark" @@ -675,10 +629,7 @@ class ImageWatermarkInvocation(BaseInvocation, PILInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Add Invisible Watermark", - "tags": ["image", "watermark", "invisible"] - }, + "ui": {"title": "Add Invisible Watermark", "tags": ["image", "watermark", "invisible"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: @@ -699,6 +650,3 @@ class ImageWatermarkInvocation(BaseInvocation, PILInvocationConfig): width=image_dto.width, height=image_dto.height, ) - - - diff --git a/invokeai/app/invocations/infill.py b/invokeai/app/invocations/infill.py index ff8900fc50..cd5b2f9a11 100644 --- a/invokeai/app/invocations/infill.py +++ b/invokeai/app/invocations/infill.py @@ -30,9 +30,7 @@ def infill_methods() -> list[str]: INFILL_METHODS = Literal[tuple(infill_methods())] -DEFAULT_INFILL_METHOD = ( - "patchmatch" if "patchmatch" in get_args(INFILL_METHODS) else "tile" -) +DEFAULT_INFILL_METHOD = "patchmatch" if "patchmatch" in get_args(INFILL_METHODS) else "tile" def infill_patchmatch(im: Image.Image) -> Image.Image: @@ -44,9 +42,7 @@ def infill_patchmatch(im: Image.Image) -> Image.Image: return im # Patchmatch (note, we may want to expose patch_size? Increasing it significantly impacts performance though) - im_patched_np = PatchMatch.inpaint( - im.convert("RGB"), ImageOps.invert(im.split()[-1]), patch_size=3 - ) + im_patched_np = PatchMatch.inpaint(im.convert("RGB"), ImageOps.invert(im.split()[-1]), patch_size=3) im_patched = Image.fromarray(im_patched_np, mode="RGB") return im_patched @@ -68,9 +64,7 @@ def get_tile_images(image: np.ndarray, width=8, height=8): ) -def tile_fill_missing( - im: Image.Image, tile_size: int = 16, seed: Optional[int] = None -) -> Image.Image: +def tile_fill_missing(im: Image.Image, tile_size: int = 16, seed: Optional[int] = None) -> Image.Image: # Only fill if there's an alpha layer if im.mode != "RGBA": return im @@ -103,9 +97,7 @@ def tile_fill_missing( # Find all invalid tiles and replace with a random valid tile replace_count = (tiles_mask == False).sum() rng = np.random.default_rng(seed=seed) - tiles_all[np.logical_not(tiles_mask)] = filtered_tiles[ - rng.choice(filtered_tiles.shape[0], replace_count), :, :, : - ] + tiles_all[np.logical_not(tiles_mask)] = filtered_tiles[rng.choice(filtered_tiles.shape[0], replace_count), :, :, :] # Convert back to an image tiles_all = tiles_all.reshape(tshape) @@ -126,9 +118,7 @@ class InfillColorInvocation(BaseInvocation): """Infills transparent areas of an image with a solid color""" type: Literal["infill_rgba"] = "infill_rgba" - image: Optional[ImageField] = Field( - default=None, description="The image to infill" - ) + image: Optional[ImageField] = Field(default=None, description="The image to infill") color: ColorField = Field( default=ColorField(r=127, g=127, b=127, a=255), description="The color to use to infill", @@ -136,10 +126,7 @@ class InfillColorInvocation(BaseInvocation): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Color Infill", - "tags": ["image", "inpaint", "color", "infill"] - }, + "ui": {"title": "Color Infill", "tags": ["image", "inpaint", "color", "infill"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: @@ -171,9 +158,7 @@ class InfillTileInvocation(BaseInvocation): type: Literal["infill_tile"] = "infill_tile" - image: Optional[ImageField] = Field( - default=None, description="The image to infill" - ) + image: Optional[ImageField] = Field(default=None, description="The image to infill") tile_size: int = Field(default=32, ge=1, description="The tile size (px)") seed: int = Field( ge=0, @@ -184,18 +169,13 @@ class InfillTileInvocation(BaseInvocation): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Tile Infill", - "tags": ["image", "inpaint", "tile", "infill"] - }, + "ui": {"title": "Tile Infill", "tags": ["image", "inpaint", "tile", "infill"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: image = context.services.images.get_pil_image(self.image.image_name) - infilled = tile_fill_missing( - image.copy(), seed=self.seed, tile_size=self.tile_size - ) + infilled = tile_fill_missing(image.copy(), seed=self.seed, tile_size=self.tile_size) infilled.paste(image, (0, 0), image.split()[-1]) image_dto = context.services.images.create( @@ -219,16 +199,11 @@ class InfillPatchMatchInvocation(BaseInvocation): type: Literal["infill_patchmatch"] = "infill_patchmatch" - image: Optional[ImageField] = Field( - default=None, description="The image to infill" - ) + image: Optional[ImageField] = Field(default=None, description="The image to infill") class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Patch Match Infill", - "tags": ["image", "inpaint", "patchmatch", "infill"] - }, + "ui": {"title": "Patch Match Infill", "tags": ["image", "inpaint", "patchmatch", "infill"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: diff --git a/invokeai/app/invocations/latent.py b/invokeai/app/invocations/latent.py index 69dffef09f..d6391e4f77 100644 --- a/invokeai/app/invocations/latent.py +++ b/invokeai/app/invocations/latent.py @@ -12,20 +12,21 @@ from pydantic import BaseModel, Field, validator from invokeai.app.invocations.metadata import CoreMetadata from invokeai.app.util.step_callback import stable_diffusion_step_callback -from invokeai.backend.model_management.models.base import ModelType +from invokeai.backend.model_management.models import ModelType, SilenceWarnings from ...backend.model_management.lora import ModelPatcher from ...backend.stable_diffusion import PipelineIntermediateState from ...backend.stable_diffusion.diffusers_pipeline import ( - ConditioningData, ControlNetData, StableDiffusionGeneratorPipeline, - image_resized_to_grid_as_tensor) -from ...backend.stable_diffusion.diffusion.shared_invokeai_diffusion import \ - PostprocessingSettings + ConditioningData, + ControlNetData, + StableDiffusionGeneratorPipeline, + image_resized_to_grid_as_tensor, +) +from ...backend.stable_diffusion.diffusion.shared_invokeai_diffusion import PostprocessingSettings from ...backend.stable_diffusion.schedulers import SCHEDULER_MAP from ...backend.util.devices import choose_torch_device, torch_dtype, choose_precision from ..models.image import ImageCategory, ImageField, ResourceOrigin -from .baseinvocation import (BaseInvocation, BaseInvocationOutput, - InvocationConfig, InvocationContext) +from .baseinvocation import BaseInvocation, BaseInvocationOutput, InvocationConfig, InvocationContext from .compel import ConditioningField from .controlnet_image_processors import ControlField from .image import ImageOutput @@ -46,8 +47,7 @@ DEFAULT_PRECISION = choose_precision(choose_torch_device()) class LatentsField(BaseModel): """A latents field used for passing latents between invocations""" - latents_name: Optional[str] = Field( - default=None, description="The name of the latents") + latents_name: Optional[str] = Field(default=None, description="The name of the latents") class Config: schema_extra = {"required": ["latents_name"]} @@ -55,14 +55,15 @@ class LatentsField(BaseModel): class LatentsOutput(BaseInvocationOutput): """Base class for invocations that output latents""" - #fmt: off + + # fmt: off type: Literal["latents_output"] = "latents_output" # Inputs latents: LatentsField = Field(default=None, description="The output latents") width: int = Field(description="The width of the latents in pixels") height: int = Field(description="The height of the latents in pixels") - #fmt: on + # fmt: on def build_latents_output(latents_name: str, latents: torch.Tensor): @@ -73,9 +74,7 @@ def build_latents_output(latents_name: str, latents: torch.Tensor): ) -SAMPLER_NAME_VALUES = Literal[ - tuple(list(SCHEDULER_MAP.keys())) -] +SAMPLER_NAME_VALUES = Literal[tuple(list(SCHEDULER_MAP.keys()))] def get_scheduler( @@ -83,11 +82,10 @@ def get_scheduler( scheduler_info: ModelInfo, scheduler_name: str, ) -> Scheduler: - scheduler_class, scheduler_extra_config = SCHEDULER_MAP.get( - scheduler_name, SCHEDULER_MAP['ddim'] - ) + scheduler_class, scheduler_extra_config = SCHEDULER_MAP.get(scheduler_name, SCHEDULER_MAP["ddim"]) orig_scheduler_info = context.services.model_manager.get_model( - **scheduler_info.dict(), context=context, + **scheduler_info.dict(), + context=context, ) with orig_scheduler_info as orig_scheduler: scheduler_config = orig_scheduler.config @@ -102,7 +100,7 @@ def get_scheduler( scheduler = scheduler_class.from_config(scheduler_config) # hack copied over from generate.py - if not hasattr(scheduler, 'uses_inpainting_model'): + if not hasattr(scheduler, "uses_inpainting_model"): scheduler.uses_inpainting_model = lambda: False return scheduler @@ -123,8 +121,8 @@ class TextToLatentsInvocation(BaseInvocation): scheduler: SAMPLER_NAME_VALUES = Field(default="euler", description="The scheduler to use" ) unet: UNetField = Field(default=None, description="UNet submodel") control: Union[ControlField, list[ControlField]] = Field(default=None, description="The control to use") - #seamless: bool = Field(default=False, description="Whether or not to generate an image that can tile without seams", ) - #seamless_axes: str = Field(default="", description="The axes to tile the image on, 'x' and/or 'y'") + # seamless: bool = Field(default=False, description="Whether or not to generate an image that can tile without seams", ) + # seamless_axes: str = Field(default="", description="The axes to tile the image on, 'x' and/or 'y'") # fmt: on @validator("cfg_scale") @@ -133,10 +131,10 @@ class TextToLatentsInvocation(BaseInvocation): if isinstance(v, list): for i in v: if i < 1: - raise ValueError('cfg_scale must be greater than 1') + raise ValueError("cfg_scale must be greater than 1") else: if v < 1: - raise ValueError('cfg_scale must be greater than 1') + raise ValueError("cfg_scale must be greater than 1") return v # Schema customisation @@ -149,8 +147,8 @@ class TextToLatentsInvocation(BaseInvocation): "model": "model", "control": "control", # "cfg_scale": "float", - "cfg_scale": "number" - } + "cfg_scale": "number", + }, }, } @@ -190,16 +188,14 @@ class TextToLatentsInvocation(BaseInvocation): threshold=0.0, # threshold, warmup=0.2, # warmup, h_symmetry_time_pct=None, # h_symmetry_time_pct, - v_symmetry_time_pct=None # v_symmetry_time_pct, + v_symmetry_time_pct=None, # v_symmetry_time_pct, ), ) conditioning_data = conditioning_data.add_scheduler_args_if_applicable( scheduler, - # for ddim scheduler eta=0.0, # ddim_eta - # for ancestral and sde schedulers generator=torch.Generator(device=unet.device).manual_seed(0), ) @@ -247,7 +243,6 @@ class TextToLatentsInvocation(BaseInvocation): exit_stack: ExitStack, do_classifier_free_guidance: bool = True, ) -> List[ControlNetData]: - # assuming fixed dimensional scaling of 8:1 for image:latents control_height_resize = latents_shape[2] * 8 control_width_resize = latents_shape[3] * 8 @@ -261,7 +256,7 @@ class TextToLatentsInvocation(BaseInvocation): control_list = control_input else: control_list = None - if (control_list is None): + if control_list is None: control_data = None # from above handling, any control that is not None should now be of type list[ControlField] else: @@ -281,9 +276,7 @@ class TextToLatentsInvocation(BaseInvocation): control_models.append(control_model) control_image_field = control_info.image - input_image = context.services.images.get_pil_image( - control_image_field.image_name - ) + input_image = context.services.images.get_pil_image(control_image_field.image_name) # self.image.image_type, self.image.image_name # FIXME: still need to test with different widths, heights, devices, dtypes # and add in batch_size, num_images_per_prompt? @@ -318,69 +311,71 @@ class TextToLatentsInvocation(BaseInvocation): @torch.no_grad() def invoke(self, context: InvocationContext) -> LatentsOutput: - noise = context.services.latents.get(self.noise.latents_name) + with SilenceWarnings(): + noise = context.services.latents.get(self.noise.latents_name) - # Get the source node id (we are invoking the prepared node) - graph_execution_state = context.services.graph_execution_manager.get( - context.graph_execution_state_id - ) - source_node_id = graph_execution_state.prepared_source_mapping[self.id] + # Get the source node id (we are invoking the prepared node) + graph_execution_state = context.services.graph_execution_manager.get(context.graph_execution_state_id) + source_node_id = graph_execution_state.prepared_source_mapping[self.id] - def step_callback(state: PipelineIntermediateState): - self.dispatch_progress(context, source_node_id, state) + def step_callback(state: PipelineIntermediateState): + self.dispatch_progress(context, source_node_id, state) - def _lora_loader(): - for lora in self.unet.loras: - lora_info = context.services.model_manager.get_model( - **lora.dict(exclude={"weight"}), context=context, - ) - yield (lora_info.context.model, lora.weight) - del lora_info - return + def _lora_loader(): + for lora in self.unet.loras: + lora_info = context.services.model_manager.get_model( + **lora.dict(exclude={"weight"}), + context=context, + ) + yield (lora_info.context.model, lora.weight) + del lora_info + return - unet_info = context.services.model_manager.get_model( - **self.unet.unet.dict(), context=context, - ) - with ExitStack() as exit_stack,\ - ModelPatcher.apply_lora_unet(unet_info.context.model, _lora_loader()),\ - unet_info as unet: - - noise = noise.to(device=unet.device, dtype=unet.dtype) - - scheduler = get_scheduler( + unet_info = context.services.model_manager.get_model( + **self.unet.unet.dict(), context=context, - scheduler_info=self.unet.scheduler, - scheduler_name=self.scheduler, ) + with ExitStack() as exit_stack, ModelPatcher.apply_lora_unet( + unet_info.context.model, _lora_loader() + ), unet_info as unet: + noise = noise.to(device=unet.device, dtype=unet.dtype) - pipeline = self.create_pipeline(unet, scheduler) - conditioning_data = self.get_conditioning_data(context, scheduler, unet) + scheduler = get_scheduler( + context=context, + scheduler_info=self.unet.scheduler, + scheduler_name=self.scheduler, + ) - control_data = self.prep_control_data( - model=pipeline, context=context, control_input=self.control, - latents_shape=noise.shape, - # do_classifier_free_guidance=(self.cfg_scale >= 1.0)) - do_classifier_free_guidance=True, - exit_stack=exit_stack, - ) + pipeline = self.create_pipeline(unet, scheduler) + conditioning_data = self.get_conditioning_data(context, scheduler, unet) - # TODO: Verify the noise is the right size - result_latents, result_attention_map_saver = pipeline.latents_from_embeddings( - latents=torch.zeros_like(noise, dtype=torch_dtype(unet.device)), - noise=noise, - num_inference_steps=self.steps, - conditioning_data=conditioning_data, - control_data=control_data, # list[ControlNetData] - callback=step_callback, - ) + control_data = self.prep_control_data( + model=pipeline, + context=context, + control_input=self.control, + latents_shape=noise.shape, + # do_classifier_free_guidance=(self.cfg_scale >= 1.0)) + do_classifier_free_guidance=True, + exit_stack=exit_stack, + ) - # https://discuss.huggingface.co/t/memory-usage-by-later-pipeline-stages/23699 - result_latents = result_latents.to("cpu") - torch.cuda.empty_cache() + # TODO: Verify the noise is the right size + result_latents, result_attention_map_saver = pipeline.latents_from_embeddings( + latents=torch.zeros_like(noise, dtype=torch_dtype(unet.device)), + noise=noise, + num_inference_steps=self.steps, + conditioning_data=conditioning_data, + control_data=control_data, # list[ControlNetData] + callback=step_callback, + ) - name = f'{context.graph_execution_state_id}__{self.id}' - context.services.latents.save(name, result_latents) - return build_latents_output(latents_name=name, latents=result_latents) + # https://discuss.huggingface.co/t/memory-usage-by-later-pipeline-stages/23699 + result_latents = result_latents.to("cpu") + torch.cuda.empty_cache() + + name = f"{context.graph_execution_state_id}__{self.id}" + context.services.latents.save(name, result_latents) + return build_latents_output(latents_name=name, latents=result_latents) class LatentsToLatentsInvocation(TextToLatentsInvocation): @@ -389,11 +384,8 @@ class LatentsToLatentsInvocation(TextToLatentsInvocation): type: Literal["l2l"] = "l2l" # Inputs - latents: Optional[LatentsField] = Field( - description="The latents to use as a base image") - strength: float = Field( - default=0.7, ge=0, le=1, - description="The strength of the latents to use") + latents: Optional[LatentsField] = Field(description="The latents to use as a base image") + strength: float = Field(default=0.7, ge=0, le=1, description="The strength of the latents to use") # Schema customisation class Config(InvocationConfig): @@ -405,87 +397,89 @@ class LatentsToLatentsInvocation(TextToLatentsInvocation): "model": "model", "control": "control", "cfg_scale": "number", - } + }, }, } @torch.no_grad() def invoke(self, context: InvocationContext) -> LatentsOutput: - noise = context.services.latents.get(self.noise.latents_name) - latent = context.services.latents.get(self.latents.latents_name) + with SilenceWarnings(): # this quenches NSFW nag from diffusers + noise = context.services.latents.get(self.noise.latents_name) + latent = context.services.latents.get(self.latents.latents_name) - # Get the source node id (we are invoking the prepared node) - graph_execution_state = context.services.graph_execution_manager.get( - context.graph_execution_state_id - ) - source_node_id = graph_execution_state.prepared_source_mapping[self.id] + # Get the source node id (we are invoking the prepared node) + graph_execution_state = context.services.graph_execution_manager.get(context.graph_execution_state_id) + source_node_id = graph_execution_state.prepared_source_mapping[self.id] - def step_callback(state: PipelineIntermediateState): - self.dispatch_progress(context, source_node_id, state) + def step_callback(state: PipelineIntermediateState): + self.dispatch_progress(context, source_node_id, state) - def _lora_loader(): - for lora in self.unet.loras: - lora_info = context.services.model_manager.get_model( - **lora.dict(exclude={"weight"}), context=context, - ) - yield (lora_info.context.model, lora.weight) - del lora_info - return + def _lora_loader(): + for lora in self.unet.loras: + lora_info = context.services.model_manager.get_model( + **lora.dict(exclude={"weight"}), + context=context, + ) + yield (lora_info.context.model, lora.weight) + del lora_info + return - unet_info = context.services.model_manager.get_model( - **self.unet.unet.dict(), context=context, - ) - with ExitStack() as exit_stack,\ - ModelPatcher.apply_lora_unet(unet_info.context.model, _lora_loader()),\ - unet_info as unet: - - noise = noise.to(device=unet.device, dtype=unet.dtype) - latent = latent.to(device=unet.device, dtype=unet.dtype) - - scheduler = get_scheduler( + unet_info = context.services.model_manager.get_model( + **self.unet.unet.dict(), context=context, - scheduler_info=self.unet.scheduler, - scheduler_name=self.scheduler, ) + with ExitStack() as exit_stack, ModelPatcher.apply_lora_unet( + unet_info.context.model, _lora_loader() + ), unet_info as unet: + noise = noise.to(device=unet.device, dtype=unet.dtype) + latent = latent.to(device=unet.device, dtype=unet.dtype) - pipeline = self.create_pipeline(unet, scheduler) - conditioning_data = self.get_conditioning_data(context, scheduler, unet) + scheduler = get_scheduler( + context=context, + scheduler_info=self.unet.scheduler, + scheduler_name=self.scheduler, + ) - control_data = self.prep_control_data( - model=pipeline, context=context, control_input=self.control, - latents_shape=noise.shape, - # do_classifier_free_guidance=(self.cfg_scale >= 1.0)) - do_classifier_free_guidance=True, - exit_stack=exit_stack, - ) + pipeline = self.create_pipeline(unet, scheduler) + conditioning_data = self.get_conditioning_data(context, scheduler, unet) - # TODO: Verify the noise is the right size - initial_latents = latent if self.strength < 1.0 else torch.zeros_like( - latent, device=unet.device, dtype=latent.dtype - ) + control_data = self.prep_control_data( + model=pipeline, + context=context, + control_input=self.control, + latents_shape=noise.shape, + # do_classifier_free_guidance=(self.cfg_scale >= 1.0)) + do_classifier_free_guidance=True, + exit_stack=exit_stack, + ) - timesteps, _ = pipeline.get_img2img_timesteps( - self.steps, - self.strength, - device=unet.device, - ) + # TODO: Verify the noise is the right size + initial_latents = ( + latent if self.strength < 1.0 else torch.zeros_like(latent, device=unet.device, dtype=latent.dtype) + ) - result_latents, result_attention_map_saver = pipeline.latents_from_embeddings( - latents=initial_latents, - timesteps=timesteps, - noise=noise, - num_inference_steps=self.steps, - conditioning_data=conditioning_data, - control_data=control_data, # list[ControlNetData] - callback=step_callback - ) + timesteps, _ = pipeline.get_img2img_timesteps( + self.steps, + self.strength, + device=unet.device, + ) - # https://discuss.huggingface.co/t/memory-usage-by-later-pipeline-stages/23699 - result_latents = result_latents.to("cpu") - torch.cuda.empty_cache() + result_latents, result_attention_map_saver = pipeline.latents_from_embeddings( + latents=initial_latents, + timesteps=timesteps, + noise=noise, + num_inference_steps=self.steps, + conditioning_data=conditioning_data, + control_data=control_data, # list[ControlNetData] + callback=step_callback, + ) - name = f'{context.graph_execution_state_id}__{self.id}' - context.services.latents.save(name, result_latents) + # https://discuss.huggingface.co/t/memory-usage-by-later-pipeline-stages/23699 + result_latents = result_latents.to("cpu") + torch.cuda.empty_cache() + + name = f"{context.graph_execution_state_id}__{self.id}" + context.services.latents.save(name, result_latents) return build_latents_output(latents_name=name, latents=result_latents) @@ -496,14 +490,13 @@ class LatentsToImageInvocation(BaseInvocation): type: Literal["l2i"] = "l2i" # Inputs - latents: Optional[LatentsField] = Field( - description="The latents to generate an image from") + latents: Optional[LatentsField] = Field(description="The latents to generate an image from") vae: VaeField = Field(default=None, description="Vae submodel") - tiled: bool = Field( - default=False, - description="Decode latents by overlapping tiles(less memory consumption)") - fp32: bool = Field(DEFAULT_PRECISION=='float32', description="Decode in full precision") - metadata: Optional[CoreMetadata] = Field(default=None, description="Optional core metadata to be written to the image") + tiled: bool = Field(default=False, description="Decode latents by overlaping tiles (less memory consumption)") + fp32: bool = Field(DEFAULT_PRECISION == "float32", description="Decode in full precision") + metadata: Optional[CoreMetadata] = Field( + default=None, description="Optional core metadata to be written to the image" + ) # Schema customisation class Config(InvocationConfig): @@ -519,7 +512,8 @@ class LatentsToImageInvocation(BaseInvocation): latents = context.services.latents.get(self.latents.latents_name) vae_info = context.services.model_manager.get_model( - **self.vae.vae.dict(), context=context, + **self.vae.vae.dict(), + context=context, ) with vae_info as vae: @@ -586,8 +580,7 @@ class LatentsToImageInvocation(BaseInvocation): ) -LATENTS_INTERPOLATION_MODE = Literal["nearest", "linear", - "bilinear", "bicubic", "trilinear", "area", "nearest-exact"] +LATENTS_INTERPOLATION_MODE = Literal["nearest", "linear", "bilinear", "bicubic", "trilinear", "area", "nearest-exact"] class ResizeLatentsInvocation(BaseInvocation): @@ -596,36 +589,30 @@ class ResizeLatentsInvocation(BaseInvocation): type: Literal["lresize"] = "lresize" # Inputs - latents: Optional[LatentsField] = Field( - description="The latents to resize") - width: Union[int, None] = Field(default=512, - ge=64, multiple_of=8, description="The width to resize to (px)") - height: Union[int, None] = Field(default=512, - ge=64, multiple_of=8, description="The height to resize to (px)") - mode: LATENTS_INTERPOLATION_MODE = Field( - default="bilinear", description="The interpolation mode") + latents: Optional[LatentsField] = Field(description="The latents to resize") + width: Union[int, None] = Field(default=512, ge=64, multiple_of=8, description="The width to resize to (px)") + height: Union[int, None] = Field(default=512, ge=64, multiple_of=8, description="The height to resize to (px)") + mode: LATENTS_INTERPOLATION_MODE = Field(default="bilinear", description="The interpolation mode") antialias: bool = Field( - default=False, - description="Whether or not to antialias (applied in bilinear and bicubic modes only)") + default=False, description="Whether or not to antialias (applied in bilinear and bicubic modes only)" + ) class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Resize Latents", - "tags": ["latents", "resize"] - }, + "ui": {"title": "Resize Latents", "tags": ["latents", "resize"]}, } def invoke(self, context: InvocationContext) -> LatentsOutput: latents = context.services.latents.get(self.latents.latents_name) # TODO: - device=choose_torch_device() + device = choose_torch_device() resized_latents = torch.nn.functional.interpolate( - latents.to(device), size=(self.height // 8, self.width // 8), - mode=self.mode, antialias=self.antialias - if self.mode in ["bilinear", "bicubic"] else False, + latents.to(device), + size=(self.height // 8, self.width // 8), + mode=self.mode, + antialias=self.antialias if self.mode in ["bilinear", "bicubic"] else False, ) # https://discuss.huggingface.co/t/memory-usage-by-later-pipeline-stages/23699 @@ -644,35 +631,30 @@ class ScaleLatentsInvocation(BaseInvocation): type: Literal["lscale"] = "lscale" # Inputs - latents: Optional[LatentsField] = Field( - description="The latents to scale") - scale_factor: float = Field( - gt=0, description="The factor by which to scale the latents") - mode: LATENTS_INTERPOLATION_MODE = Field( - default="bilinear", description="The interpolation mode") + latents: Optional[LatentsField] = Field(description="The latents to scale") + scale_factor: float = Field(gt=0, description="The factor by which to scale the latents") + mode: LATENTS_INTERPOLATION_MODE = Field(default="bilinear", description="The interpolation mode") antialias: bool = Field( - default=False, - description="Whether or not to antialias (applied in bilinear and bicubic modes only)") + default=False, description="Whether or not to antialias (applied in bilinear and bicubic modes only)" + ) class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Scale Latents", - "tags": ["latents", "scale"] - }, + "ui": {"title": "Scale Latents", "tags": ["latents", "scale"]}, } def invoke(self, context: InvocationContext) -> LatentsOutput: latents = context.services.latents.get(self.latents.latents_name) # TODO: - device=choose_torch_device() + device = choose_torch_device() # resizing resized_latents = torch.nn.functional.interpolate( - latents.to(device), scale_factor=self.scale_factor, mode=self.mode, - antialias=self.antialias - if self.mode in ["bilinear", "bicubic"] else False, + latents.to(device), + scale_factor=self.scale_factor, + mode=self.mode, + antialias=self.antialias if self.mode in ["bilinear", "bicubic"] else False, ) # https://discuss.huggingface.co/t/memory-usage-by-later-pipeline-stages/23699 @@ -693,19 +675,13 @@ class ImageToLatentsInvocation(BaseInvocation): # Inputs image: Optional[ImageField] = Field(description="The image to encode") vae: VaeField = Field(default=None, description="Vae submodel") - tiled: bool = Field( - default=False, - description="Encode latents by overlaping tiles(less memory consumption)") - fp32: bool = Field(DEFAULT_PRECISION=='float32', description="Decode in full precision") - + tiled: bool = Field(default=False, description="Encode latents by overlaping tiles(less memory consumption)") + fp32: bool = Field(DEFAULT_PRECISION == "float32", description="Decode in full precision") # Schema customisation class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Image To Latents", - "tags": ["latents", "image"] - }, + "ui": {"title": "Image To Latents", "tags": ["latents", "image"]}, } @torch.no_grad() @@ -715,9 +691,10 @@ class ImageToLatentsInvocation(BaseInvocation): # ) image = context.services.images.get_pil_image(self.image.image_name) - #vae_info = context.services.model_manager.get_model(**self.vae.vae.dict()) + # vae_info = context.services.model_manager.get_model(**self.vae.vae.dict()) vae_info = context.services.model_manager.get_model( - **self.vae.vae.dict(), context=context, + **self.vae.vae.dict(), + context=context, ) image_tensor = image_resized_to_grid_as_tensor(image.convert("RGB")) @@ -744,12 +721,12 @@ class ImageToLatentsInvocation(BaseInvocation): vae.post_quant_conv.to(orig_dtype) vae.decoder.conv_in.to(orig_dtype) vae.decoder.mid_block.to(orig_dtype) - #else: + # else: # latents = latents.float() else: vae.to(dtype=torch.float16) - #latents = latents.half() + # latents = latents.half() if self.tiled: vae.enable_tiling() @@ -760,9 +737,7 @@ class ImageToLatentsInvocation(BaseInvocation): image_tensor = image_tensor.to(device=vae.device, dtype=vae.dtype) with torch.inference_mode(): image_tensor_dist = vae.encode(image_tensor).latent_dist - latents = image_tensor_dist.sample().to( - dtype=vae.dtype - ) # FIXME: uses torch.randn. make reproducible! + latents = image_tensor_dist.sample().to(dtype=vae.dtype) # FIXME: uses torch.randn. make reproducible! latents = vae.config.scaling_factor * latents latents = latents.to(dtype=orig_dtype) diff --git a/invokeai/app/invocations/math.py b/invokeai/app/invocations/math.py index 92cff04bf7..32b1ab2a39 100644 --- a/invokeai/app/invocations/math.py +++ b/invokeai/app/invocations/math.py @@ -54,10 +54,7 @@ class AddInvocation(BaseInvocation, MathInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Add", - "tags": ["math", "add"] - }, + "ui": {"title": "Add", "tags": ["math", "add"]}, } def invoke(self, context: InvocationContext) -> IntOutput: @@ -75,10 +72,7 @@ class SubtractInvocation(BaseInvocation, MathInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Subtract", - "tags": ["math", "subtract"] - }, + "ui": {"title": "Subtract", "tags": ["math", "subtract"]}, } def invoke(self, context: InvocationContext) -> IntOutput: @@ -96,10 +90,7 @@ class MultiplyInvocation(BaseInvocation, MathInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Multiply", - "tags": ["math", "multiply"] - }, + "ui": {"title": "Multiply", "tags": ["math", "multiply"]}, } def invoke(self, context: InvocationContext) -> IntOutput: @@ -117,10 +108,7 @@ class DivideInvocation(BaseInvocation, MathInvocationConfig): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Divide", - "tags": ["math", "divide"] - }, + "ui": {"title": "Divide", "tags": ["math", "divide"]}, } def invoke(self, context: InvocationContext) -> IntOutput: @@ -140,10 +128,7 @@ class RandomIntInvocation(BaseInvocation): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Random Integer", - "tags": ["math", "random", "integer"] - }, + "ui": {"title": "Random Integer", "tags": ["math", "random", "integer"]}, } def invoke(self, context: InvocationContext) -> IntOutput: diff --git a/invokeai/app/invocations/metadata.py b/invokeai/app/invocations/metadata.py index b0742d0419..3588ef4ebe 100644 --- a/invokeai/app/invocations/metadata.py +++ b/invokeai/app/invocations/metadata.py @@ -11,6 +11,7 @@ from invokeai.app.invocations.baseinvocation import ( from invokeai.app.invocations.controlnet_image_processors import ControlField from invokeai.app.invocations.model import LoRAModelField, MainModelField, VAEModelField + class LoRAMetadataField(BaseModel): """LoRA metadata for an image generated in InvokeAI.""" @@ -37,9 +38,7 @@ class CoreMetadata(BaseModel): description="The number of skipped CLIP layers", ) model: MainModelField = Field(description="The main model used for inference") - controlnets: list[ControlField] = Field( - description="The ControlNets used for inference" - ) + controlnets: list[ControlField] = Field(description="The ControlNets used for inference") loras: list[LoRAMetadataField] = Field(description="The LoRAs used for inference") vae: Union[VAEModelField, None] = Field( default=None, @@ -51,38 +50,24 @@ class CoreMetadata(BaseModel): default=None, description="The strength used for latents-to-latents", ) - init_image: Union[str, None] = Field( - default=None, description="The name of the initial image" - ) + init_image: Union[str, None] = Field(default=None, description="The name of the initial image") # SDXL - positive_style_prompt: Union[str, None] = Field( - default=None, description="The positive style prompt parameter" - ) - negative_style_prompt: Union[str, None] = Field( - default=None, description="The negative style prompt parameter" - ) + positive_style_prompt: Union[str, None] = Field(default=None, description="The positive style prompt parameter") + negative_style_prompt: Union[str, None] = Field(default=None, description="The negative style prompt parameter") # SDXL Refiner - refiner_model: Union[MainModelField, None] = Field( - default=None, description="The SDXL Refiner model used" - ) + refiner_model: Union[MainModelField, None] = Field(default=None, description="The SDXL Refiner model used") refiner_cfg_scale: Union[float, None] = Field( default=None, description="The classifier-free guidance scale parameter used for the refiner", ) - refiner_steps: Union[int, None] = Field( - default=None, description="The number of steps used for the refiner" - ) - refiner_scheduler: Union[str, None] = Field( - default=None, description="The scheduler used for the refiner" - ) + refiner_steps: Union[int, None] = Field(default=None, description="The number of steps used for the refiner") + refiner_scheduler: Union[str, None] = Field(default=None, description="The scheduler used for the refiner") refiner_aesthetic_store: Union[float, None] = Field( default=None, description="The aesthetic score used for the refiner" ) - refiner_start: Union[float, None] = Field( - default=None, description="The start value used for refiner denoising" - ) + refiner_start: Union[float, None] = Field(default=None, description="The start value used for refiner denoising") class ImageMetadata(BaseModel): @@ -92,9 +77,7 @@ class ImageMetadata(BaseModel): default=None, description="The image's core metadata, if it was created in the Linear or Canvas UI", ) - graph: Optional[dict] = Field( - default=None, description="The graph that created the image" - ) + graph: Optional[dict] = Field(default=None, description="The graph that created the image") class MetadataAccumulatorOutput(BaseInvocationOutput): @@ -126,50 +109,34 @@ class MetadataAccumulatorInvocation(BaseInvocation): description="The number of skipped CLIP layers", ) model: MainModelField = Field(description="The main model used for inference") - controlnets: list[ControlField] = Field( - description="The ControlNets used for inference" - ) + controlnets: list[ControlField] = Field(description="The ControlNets used for inference") loras: list[LoRAMetadataField] = Field(description="The LoRAs used for inference") strength: Union[float, None] = Field( default=None, description="The strength used for latents-to-latents", ) - init_image: Union[str, None] = Field( - default=None, description="The name of the initial image" - ) + init_image: Union[str, None] = Field(default=None, description="The name of the initial image") vae: Union[VAEModelField, None] = Field( default=None, description="The VAE used for decoding, if the main model's default was not used", ) # SDXL - positive_style_prompt: Union[str, None] = Field( - default=None, description="The positive style prompt parameter" - ) - negative_style_prompt: Union[str, None] = Field( - default=None, description="The negative style prompt parameter" - ) + positive_style_prompt: Union[str, None] = Field(default=None, description="The positive style prompt parameter") + negative_style_prompt: Union[str, None] = Field(default=None, description="The negative style prompt parameter") # SDXL Refiner - refiner_model: Union[MainModelField, None] = Field( - default=None, description="The SDXL Refiner model used" - ) + refiner_model: Union[MainModelField, None] = Field(default=None, description="The SDXL Refiner model used") refiner_cfg_scale: Union[float, None] = Field( default=None, description="The classifier-free guidance scale parameter used for the refiner", ) - refiner_steps: Union[int, None] = Field( - default=None, description="The number of steps used for the refiner" - ) - refiner_scheduler: Union[str, None] = Field( - default=None, description="The scheduler used for the refiner" - ) + refiner_steps: Union[int, None] = Field(default=None, description="The number of steps used for the refiner") + refiner_scheduler: Union[str, None] = Field(default=None, description="The scheduler used for the refiner") refiner_aesthetic_store: Union[float, None] = Field( default=None, description="The aesthetic score used for the refiner" ) - refiner_start: Union[float, None] = Field( - default=None, description="The start value used for refiner denoising" - ) + refiner_start: Union[float, None] = Field(default=None, description="The start value used for refiner denoising") class Config(InvocationConfig): schema_extra = { diff --git a/invokeai/app/invocations/model.py b/invokeai/app/invocations/model.py index 5f1a91ae3b..2388d12e25 100644 --- a/invokeai/app/invocations/model.py +++ b/invokeai/app/invocations/model.py @@ -4,17 +4,14 @@ from typing import List, Literal, Optional, Union from pydantic import BaseModel, Field from ...backend.model_management import BaseModelType, ModelType, SubModelType -from .baseinvocation import (BaseInvocation, BaseInvocationOutput, - InvocationConfig, InvocationContext) +from .baseinvocation import BaseInvocation, BaseInvocationOutput, InvocationConfig, InvocationContext class ModelInfo(BaseModel): model_name: str = Field(description="Info to load submodel") base_model: BaseModelType = Field(description="Base model") model_type: ModelType = Field(description="Info to load submodel") - submodel: Optional[SubModelType] = Field( - default=None, description="Info to load submodel" - ) + submodel: Optional[SubModelType] = Field(default=None, description="Info to load submodel") class LoraInfo(ModelInfo): @@ -33,6 +30,7 @@ class ClipField(BaseModel): skipped_layers: int = Field(description="Number of skipped layers in text_encoder") loras: List[LoraInfo] = Field(description="Loras to apply on model loading") + class VaeField(BaseModel): # TODO: better naming? vae: ModelInfo = Field(description="Info to load vae submodel") @@ -49,6 +47,7 @@ class ModelLoaderOutput(BaseInvocationOutput): vae: VaeField = Field(default=None, description="Vae submodel") # fmt: on + class MainModelField(BaseModel): """Main model field""" @@ -62,6 +61,7 @@ class LoRAModelField(BaseModel): model_name: str = Field(description="Name of the LoRA model") base_model: BaseModelType = Field(description="Base model") + class MainModelLoaderInvocation(BaseInvocation): """Loads a main model, outputting its submodels.""" @@ -180,7 +180,7 @@ class MainModelLoaderInvocation(BaseInvocation): ), ) - + class LoraLoaderOutput(BaseInvocationOutput): """Model loader output""" @@ -197,9 +197,7 @@ class LoraLoaderInvocation(BaseInvocation): type: Literal["lora_loader"] = "lora_loader" - lora: Union[LoRAModelField, None] = Field( - default=None, description="Lora model name" - ) + lora: Union[LoRAModelField, None] = Field(default=None, description="Lora model name") weight: float = Field(default=0.75, description="With what weight to apply lora") unet: Optional[UNetField] = Field(description="UNet model for applying lora") @@ -228,14 +226,10 @@ class LoraLoaderInvocation(BaseInvocation): ): raise Exception(f"Unkown lora name: {lora_name}!") - if self.unet is not None and any( - lora.model_name == lora_name for lora in self.unet.loras - ): + if self.unet is not None and any(lora.model_name == lora_name for lora in self.unet.loras): raise Exception(f'Lora "{lora_name}" already applied to unet') - if self.clip is not None and any( - lora.model_name == lora_name for lora in self.clip.loras - ): + if self.clip is not None and any(lora.model_name == lora_name for lora in self.clip.loras): raise Exception(f'Lora "{lora_name}" already applied to clip') output = LoraLoaderOutput() diff --git a/invokeai/app/invocations/param_easing.py b/invokeai/app/invocations/param_easing.py index 70d3ddc7d2..f910e5379c 100644 --- a/invokeai/app/invocations/param_easing.py +++ b/invokeai/app/invocations/param_easing.py @@ -12,16 +12,37 @@ import matplotlib.pyplot as plt from easing_functions import ( LinearInOut, - QuadEaseInOut, QuadEaseIn, QuadEaseOut, - CubicEaseInOut, CubicEaseIn, CubicEaseOut, - QuarticEaseInOut, QuarticEaseIn, QuarticEaseOut, - QuinticEaseInOut, QuinticEaseIn, QuinticEaseOut, - SineEaseInOut, SineEaseIn, SineEaseOut, - CircularEaseIn, CircularEaseInOut, CircularEaseOut, - ExponentialEaseInOut, ExponentialEaseIn, ExponentialEaseOut, - ElasticEaseIn, ElasticEaseInOut, ElasticEaseOut, - BackEaseIn, BackEaseInOut, BackEaseOut, - BounceEaseIn, BounceEaseInOut, BounceEaseOut) + QuadEaseInOut, + QuadEaseIn, + QuadEaseOut, + CubicEaseInOut, + CubicEaseIn, + CubicEaseOut, + QuarticEaseInOut, + QuarticEaseIn, + QuarticEaseOut, + QuinticEaseInOut, + QuinticEaseIn, + QuinticEaseOut, + SineEaseInOut, + SineEaseIn, + SineEaseOut, + CircularEaseIn, + CircularEaseInOut, + CircularEaseOut, + ExponentialEaseInOut, + ExponentialEaseIn, + ExponentialEaseOut, + ElasticEaseIn, + ElasticEaseInOut, + ElasticEaseOut, + BackEaseIn, + BackEaseInOut, + BackEaseOut, + BounceEaseIn, + BounceEaseInOut, + BounceEaseOut, +) from .baseinvocation import ( BaseInvocation, @@ -45,17 +66,12 @@ class FloatLinearRangeInvocation(BaseInvocation): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Linear Range (Float)", - "tags": ["math", "float", "linear", "range"] - }, + "ui": {"title": "Linear Range (Float)", "tags": ["math", "float", "linear", "range"]}, } def invoke(self, context: InvocationContext) -> FloatCollectionOutput: param_list = list(np.linspace(self.start, self.stop, self.steps)) - return FloatCollectionOutput( - collection=param_list - ) + return FloatCollectionOutput(collection=param_list) EASING_FUNCTIONS_MAP = { @@ -92,9 +108,7 @@ EASING_FUNCTIONS_MAP = { "BounceInOut": BounceEaseInOut, } -EASING_FUNCTION_KEYS: Any = Literal[ - tuple(list(EASING_FUNCTIONS_MAP.keys())) -] +EASING_FUNCTION_KEYS: Any = Literal[tuple(list(EASING_FUNCTIONS_MAP.keys()))] # actually I think for now could just use CollectionOutput (which is list[Any] @@ -123,13 +137,9 @@ class StepParamEasingInvocation(BaseInvocation): class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Param Easing By Step", - "tags": ["param", "step", "easing"] - }, + "ui": {"title": "Param Easing By Step", "tags": ["param", "step", "easing"]}, } - def invoke(self, context: InvocationContext) -> FloatCollectionOutput: log_diagnostics = False # convert from start_step_percent to nearest step <= (steps * start_step_percent) @@ -170,12 +180,13 @@ class StepParamEasingInvocation(BaseInvocation): # and create reverse copy of list[1:end-1] # but if even then number_of_steps/2 === ceil(number_of_steps/2), so can just use ceil always - base_easing_duration = int(np.ceil(num_easing_steps/2.0)) - if log_diagnostics: context.services.logger.debug("base easing duration: " + str(base_easing_duration)) - even_num_steps = (num_easing_steps % 2 == 0) # even number of steps - easing_function = easing_class(start=self.start_value, - end=self.end_value, - duration=base_easing_duration - 1) + base_easing_duration = int(np.ceil(num_easing_steps / 2.0)) + if log_diagnostics: + context.services.logger.debug("base easing duration: " + str(base_easing_duration)) + even_num_steps = num_easing_steps % 2 == 0 # even number of steps + easing_function = easing_class( + start=self.start_value, end=self.end_value, duration=base_easing_duration - 1 + ) base_easing_vals = list() for step_index in range(base_easing_duration): easing_val = easing_function.ease(step_index) @@ -214,9 +225,7 @@ class StepParamEasingInvocation(BaseInvocation): # else: # no mirroring (default) - easing_function = easing_class(start=self.start_value, - end=self.end_value, - duration=num_easing_steps - 1) + easing_function = easing_class(start=self.start_value, end=self.end_value, duration=num_easing_steps - 1) for step_index in range(num_easing_steps): step_val = easing_function.ease(step_index) easing_list.append(step_val) @@ -240,13 +249,11 @@ class StepParamEasingInvocation(BaseInvocation): ax = plt.gca() ax.xaxis.set_major_locator(MaxNLocator(integer=True)) buf = io.BytesIO() - plt.savefig(buf, format='png') + plt.savefig(buf, format="png") buf.seek(0) im = PIL.Image.open(buf) im.show() buf.close() # output array of size steps, each entry list[i] is param value for step i - return FloatCollectionOutput( - collection=param_list - ) + return FloatCollectionOutput(collection=param_list) diff --git a/invokeai/app/invocations/params.py b/invokeai/app/invocations/params.py index 0f01d65948..127eefa21d 100644 --- a/invokeai/app/invocations/params.py +++ b/invokeai/app/invocations/params.py @@ -4,67 +4,63 @@ from typing import Literal from pydantic import Field -from .baseinvocation import (BaseInvocation, BaseInvocationOutput, - InvocationConfig, InvocationContext) +from .baseinvocation import BaseInvocation, BaseInvocationOutput, InvocationConfig, InvocationContext from .math import FloatOutput, IntOutput # Pass-through parameter nodes - used by subgraphs + class ParamIntInvocation(BaseInvocation): """An integer parameter""" - #fmt: off + + # fmt: off type: Literal["param_int"] = "param_int" a: int = Field(default=0, description="The integer value") - #fmt: on + # fmt: on class Config(InvocationConfig): - schema_extra = { - "ui": { - "tags": ["param", "integer"], - "title": "Integer Parameter" - }, - } + schema_extra = { + "ui": {"tags": ["param", "integer"], "title": "Integer Parameter"}, + } def invoke(self, context: InvocationContext) -> IntOutput: return IntOutput(a=self.a) + class ParamFloatInvocation(BaseInvocation): """A float parameter""" - #fmt: off + + # fmt: off type: Literal["param_float"] = "param_float" param: float = Field(default=0.0, description="The float value") - #fmt: on + # fmt: on class Config(InvocationConfig): - schema_extra = { - "ui": { - "tags": ["param", "float"], - "title": "Float Parameter" - }, - } + schema_extra = { + "ui": {"tags": ["param", "float"], "title": "Float Parameter"}, + } def invoke(self, context: InvocationContext) -> FloatOutput: return FloatOutput(param=self.param) + class StringOutput(BaseInvocationOutput): """A string output""" + type: Literal["string_output"] = "string_output" text: str = Field(default=None, description="The output string") class ParamStringInvocation(BaseInvocation): """A string parameter""" - type: Literal['param_string'] = 'param_string' - text: str = Field(default='', description='The string value') + + type: Literal["param_string"] = "param_string" + text: str = Field(default="", description="The string value") class Config(InvocationConfig): - schema_extra = { - "ui": { - "tags": ["param", "string"], - "title": "String Parameter" - }, - } + schema_extra = { + "ui": {"tags": ["param", "string"], "title": "String Parameter"}, + } def invoke(self, context: InvocationContext) -> StringOutput: return StringOutput(text=self.text) - \ No newline at end of file diff --git a/invokeai/app/invocations/prompt.py b/invokeai/app/invocations/prompt.py index 5d07a88759..83a397ddcf 100644 --- a/invokeai/app/invocations/prompt.py +++ b/invokeai/app/invocations/prompt.py @@ -7,19 +7,21 @@ from pydantic import Field, validator from .baseinvocation import BaseInvocation, BaseInvocationOutput, InvocationConfig, InvocationContext from dynamicprompts.generators import RandomPromptGenerator, CombinatorialPromptGenerator + class PromptOutput(BaseInvocationOutput): """Base class for invocations that output a prompt""" - #fmt: off + + # fmt: off type: Literal["prompt"] = "prompt" prompt: str = Field(default=None, description="The output prompt") - #fmt: on + # fmt: on class Config: schema_extra = { - 'required': [ - 'type', - 'prompt', + "required": [ + "type", + "prompt", ] } @@ -44,16 +46,11 @@ class DynamicPromptInvocation(BaseInvocation): type: Literal["dynamic_prompt"] = "dynamic_prompt" prompt: str = Field(description="The prompt to parse with dynamicprompts") max_prompts: int = Field(default=1, description="The number of prompts to generate") - combinatorial: bool = Field( - default=False, description="Whether to use the combinatorial generator" - ) + combinatorial: bool = Field(default=False, description="Whether to use the combinatorial generator") class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Dynamic Prompt", - "tags": ["prompt", "dynamic"] - }, + "ui": {"title": "Dynamic Prompt", "tags": ["prompt", "dynamic"]}, } def invoke(self, context: InvocationContext) -> PromptCollectionOutput: @@ -65,10 +62,11 @@ class DynamicPromptInvocation(BaseInvocation): prompts = generator.generate(self.prompt, num_images=self.max_prompts) return PromptCollectionOutput(prompt_collection=prompts, count=len(prompts)) - + class PromptsFromFileInvocation(BaseInvocation): - '''Loads prompts from a text file''' + """Loads prompts from a text file""" + # fmt: off type: Literal['prompt_from_file'] = 'prompt_from_file' @@ -78,14 +76,11 @@ class PromptsFromFileInvocation(BaseInvocation): post_prompt: Optional[str] = Field(description="String to append to each prompt") start_line: int = Field(default=1, ge=1, description="Line in the file to start start from") max_prompts: int = Field(default=1, ge=0, description="Max lines to read from file (0=all)") - #fmt: on + # fmt: on class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Prompts From File", - "tags": ["prompt", "file"] - }, + "ui": {"title": "Prompts From File", "tags": ["prompt", "file"]}, } @validator("file_path") @@ -103,11 +98,13 @@ class PromptsFromFileInvocation(BaseInvocation): with open(file_path) as f: for i, line in enumerate(f): if i >= start_line and i < end_line: - prompts.append((pre_prompt or '') + line.strip() + (post_prompt or '')) + prompts.append((pre_prompt or "") + line.strip() + (post_prompt or "")) if i >= end_line: break return prompts def invoke(self, context: InvocationContext) -> PromptCollectionOutput: - prompts = self.promptsFromFile(self.file_path, self.pre_prompt, self.post_prompt, self.start_line, self.max_prompts) + prompts = self.promptsFromFile( + self.file_path, self.pre_prompt, self.post_prompt, self.start_line, self.max_prompts + ) return PromptCollectionOutput(prompt_collection=prompts, count=len(prompts)) diff --git a/invokeai/app/invocations/sdxl.py b/invokeai/app/invocations/sdxl.py index 3b4d3a9d86..303a2fedd9 100644 --- a/invokeai/app/invocations/sdxl.py +++ b/invokeai/app/invocations/sdxl.py @@ -7,13 +7,13 @@ from pydantic import Field, validator from ...backend.model_management import ModelType, SubModelType from invokeai.app.util.step_callback import stable_diffusion_xl_step_callback -from .baseinvocation import (BaseInvocation, BaseInvocationOutput, - InvocationConfig, InvocationContext) +from .baseinvocation import BaseInvocation, BaseInvocationOutput, InvocationConfig, InvocationContext from .model import UNetField, ClipField, VaeField, MainModelField, ModelInfo from .compel import ConditioningField from .latent import LatentsField, SAMPLER_NAME_VALUES, LatentsOutput, get_scheduler, build_latents_output + class SDXLModelLoaderOutput(BaseInvocationOutput): """SDXL base model loader output""" @@ -26,16 +26,19 @@ class SDXLModelLoaderOutput(BaseInvocationOutput): vae: VaeField = Field(default=None, description="Vae submodel") # fmt: on + class SDXLRefinerModelLoaderOutput(BaseInvocationOutput): """SDXL refiner model loader output""" + # fmt: off type: Literal["sdxl_refiner_model_loader_output"] = "sdxl_refiner_model_loader_output" unet: UNetField = Field(default=None, description="UNet submodel") clip2: ClipField = Field(default=None, description="Tokenizer and text_encoder submodels") vae: VaeField = Field(default=None, description="Vae submodel") # fmt: on - #fmt: on - + # fmt: on + + class SDXLModelLoaderInvocation(BaseInvocation): """Loads an sdxl base model, outputting its submodels.""" @@ -125,8 +128,10 @@ class SDXLModelLoaderInvocation(BaseInvocation): ), ) + class SDXLRefinerModelLoaderInvocation(BaseInvocation): """Loads an sdxl refiner model, outputting its submodels.""" + type: Literal["sdxl_refiner_model_loader"] = "sdxl_refiner_model_loader" model: MainModelField = Field(description="The model to load") @@ -196,7 +201,8 @@ class SDXLRefinerModelLoaderInvocation(BaseInvocation): ), ), ) - + + # Text to image class SDXLTextToLatentsInvocation(BaseInvocation): """Generates latents from conditionings.""" @@ -213,9 +219,9 @@ class SDXLTextToLatentsInvocation(BaseInvocation): scheduler: SAMPLER_NAME_VALUES = Field(default="euler", description="The scheduler to use" ) unet: UNetField = Field(default=None, description="UNet submodel") denoising_end: float = Field(default=1.0, gt=0, le=1, description="") - #control: Union[ControlField, list[ControlField]] = Field(default=None, description="The control to use") - #seamless: bool = Field(default=False, description="Whether or not to generate an image that can tile without seams", ) - #seamless_axes: str = Field(default="", description="The axes to tile the image on, 'x' and/or 'y'") + # control: Union[ControlField, list[ControlField]] = Field(default=None, description="The control to use") + # seamless: bool = Field(default=False, description="Whether or not to generate an image that can tile without seams", ) + # seamless_axes: str = Field(default="", description="The axes to tile the image on, 'x' and/or 'y'") # fmt: on @validator("cfg_scale") @@ -224,10 +230,10 @@ class SDXLTextToLatentsInvocation(BaseInvocation): if isinstance(v, list): for i in v: if i < 1: - raise ValueError('cfg_scale must be greater than 1') + raise ValueError("cfg_scale must be greater than 1") else: if v < 1: - raise ValueError('cfg_scale must be greater than 1') + raise ValueError("cfg_scale must be greater than 1") return v # Schema customisation @@ -237,10 +243,10 @@ class SDXLTextToLatentsInvocation(BaseInvocation): "title": "SDXL Text To Latents", "tags": ["latents"], "type_hints": { - "model": "model", - # "cfg_scale": "float", - "cfg_scale": "number" - } + "model": "model", + # "cfg_scale": "float", + "cfg_scale": "number", + }, }, } @@ -265,9 +271,7 @@ class SDXLTextToLatentsInvocation(BaseInvocation): # https://github.com/huggingface/diffusers/blob/3ebbaf7c96801271f9e6c21400033b6aa5ffcf29/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py#L375 @torch.no_grad() def invoke(self, context: InvocationContext) -> LatentsOutput: - graph_execution_state = context.services.graph_execution_manager.get( - context.graph_execution_state_id - ) + graph_execution_state = context.services.graph_execution_manager.get(context.graph_execution_state_id) source_node_id = graph_execution_state.prepared_source_mapping[self.id] latents = context.services.latents.get(self.noise.latents_name) @@ -293,14 +297,10 @@ class SDXLTextToLatentsInvocation(BaseInvocation): latents = latents * scheduler.init_noise_sigma - - unet_info = context.services.model_manager.get_model( - **self.unet.unet.dict(), context=context - ) + unet_info = context.services.model_manager.get_model(**self.unet.unet.dict(), context=context) do_classifier_free_guidance = True cross_attention_kwargs = None with unet_info as unet: - extra_step_kwargs = dict() if "eta" in set(inspect.signature(scheduler.step).parameters.keys()): extra_step_kwargs.update( @@ -350,10 +350,10 @@ class SDXLTextToLatentsInvocation(BaseInvocation): if do_classifier_free_guidance: noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + self.cfg_scale * (noise_pred_text - noise_pred_uncond) - #del noise_pred_uncond - #del noise_pred_text + # del noise_pred_uncond + # del noise_pred_text - #if do_classifier_free_guidance and guidance_rescale > 0.0: + # if do_classifier_free_guidance and guidance_rescale > 0.0: # # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf # noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale) @@ -364,7 +364,7 @@ class SDXLTextToLatentsInvocation(BaseInvocation): if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % scheduler.order == 0): progress_bar.update() self.dispatch_progress(context, source_node_id, latents, i, num_inference_steps) - #if callback is not None and i % callback_steps == 0: + # if callback is not None and i % callback_steps == 0: # callback(i, t, latents) else: negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.to(device=unet.device, dtype=unet.dtype) @@ -378,13 +378,13 @@ class SDXLTextToLatentsInvocation(BaseInvocation): with tqdm(total=num_inference_steps) as progress_bar: for i, t in enumerate(timesteps): # expand the latents if we are doing classifier free guidance - #latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents + # latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents latent_model_input = scheduler.scale_model_input(latents, t) - #import gc - #gc.collect() - #torch.cuda.empty_cache() + # import gc + # gc.collect() + # torch.cuda.empty_cache() # predict the noise residual @@ -411,42 +411,41 @@ class SDXLTextToLatentsInvocation(BaseInvocation): # perform guidance noise_pred = noise_pred_uncond + self.cfg_scale * (noise_pred_text - noise_pred_uncond) - #del noise_pred_text - #del noise_pred_uncond - #import gc - #gc.collect() - #torch.cuda.empty_cache() + # del noise_pred_text + # del noise_pred_uncond + # import gc + # gc.collect() + # torch.cuda.empty_cache() - #if do_classifier_free_guidance and guidance_rescale > 0.0: + # if do_classifier_free_guidance and guidance_rescale > 0.0: # # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf # noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale) # compute the previous noisy sample x_t -> x_t-1 latents = scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0] - #del noise_pred - #import gc - #gc.collect() - #torch.cuda.empty_cache() + # del noise_pred + # import gc + # gc.collect() + # torch.cuda.empty_cache() # call the callback, if provided if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % scheduler.order == 0): progress_bar.update() self.dispatch_progress(context, source_node_id, latents, i, num_inference_steps) - #if callback is not None and i % callback_steps == 0: + # if callback is not None and i % callback_steps == 0: # callback(i, t, latents) - - ################# latents = latents.to("cpu") torch.cuda.empty_cache() - name = f'{context.graph_execution_state_id}__{self.id}' + name = f"{context.graph_execution_state_id}__{self.id}" context.services.latents.save(name, latents) return build_latents_output(latents_name=name, latents=latents) + class SDXLLatentsToLatentsInvocation(BaseInvocation): """Generates latents from conditionings.""" @@ -466,9 +465,9 @@ class SDXLLatentsToLatentsInvocation(BaseInvocation): denoising_start: float = Field(default=0.0, ge=0, le=1, description="") denoising_end: float = Field(default=1.0, ge=0, le=1, description="") - #control: Union[ControlField, list[ControlField]] = Field(default=None, description="The control to use") - #seamless: bool = Field(default=False, description="Whether or not to generate an image that can tile without seams", ) - #seamless_axes: str = Field(default="", description="The axes to tile the image on, 'x' and/or 'y'") + # control: Union[ControlField, list[ControlField]] = Field(default=None, description="The control to use") + # seamless: bool = Field(default=False, description="Whether or not to generate an image that can tile without seams", ) + # seamless_axes: str = Field(default="", description="The axes to tile the image on, 'x' and/or 'y'") # fmt: on @validator("cfg_scale") @@ -477,10 +476,10 @@ class SDXLLatentsToLatentsInvocation(BaseInvocation): if isinstance(v, list): for i in v: if i < 1: - raise ValueError('cfg_scale must be greater than 1') + raise ValueError("cfg_scale must be greater than 1") else: if v < 1: - raise ValueError('cfg_scale must be greater than 1') + raise ValueError("cfg_scale must be greater than 1") return v # Schema customisation @@ -490,10 +489,10 @@ class SDXLLatentsToLatentsInvocation(BaseInvocation): "title": "SDXL Latents to Latents", "tags": ["latents"], "type_hints": { - "model": "model", - # "cfg_scale": "float", - "cfg_scale": "number" - } + "model": "model", + # "cfg_scale": "float", + "cfg_scale": "number", + }, }, } @@ -518,9 +517,7 @@ class SDXLLatentsToLatentsInvocation(BaseInvocation): # https://github.com/huggingface/diffusers/blob/3ebbaf7c96801271f9e6c21400033b6aa5ffcf29/src/diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py#L375 @torch.no_grad() def invoke(self, context: InvocationContext) -> LatentsOutput: - graph_execution_state = context.services.graph_execution_manager.get( - context.graph_execution_state_id - ) + graph_execution_state = context.services.graph_execution_manager.get(context.graph_execution_state_id) source_node_id = graph_execution_state.prepared_source_mapping[self.id] latents = context.services.latents.get(self.latents.latents_name) @@ -545,7 +542,7 @@ class SDXLLatentsToLatentsInvocation(BaseInvocation): scheduler.set_timesteps(num_inference_steps) t_start = int(round(self.denoising_start * num_inference_steps)) - timesteps = scheduler.timesteps[t_start * scheduler.order:] + timesteps = scheduler.timesteps[t_start * scheduler.order :] num_inference_steps = num_inference_steps - t_start # apply noise(if provided) @@ -555,12 +552,12 @@ class SDXLLatentsToLatentsInvocation(BaseInvocation): del noise unet_info = context.services.model_manager.get_model( - **self.unet.unet.dict(), context=context, + **self.unet.unet.dict(), + context=context, ) do_classifier_free_guidance = True cross_attention_kwargs = None with unet_info as unet: - # apply scheduler extra args extra_step_kwargs = dict() if "eta" in set(inspect.signature(scheduler.step).parameters.keys()): @@ -611,10 +608,10 @@ class SDXLLatentsToLatentsInvocation(BaseInvocation): if do_classifier_free_guidance: noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + self.cfg_scale * (noise_pred_text - noise_pred_uncond) - #del noise_pred_uncond - #del noise_pred_text + # del noise_pred_uncond + # del noise_pred_text - #if do_classifier_free_guidance and guidance_rescale > 0.0: + # if do_classifier_free_guidance and guidance_rescale > 0.0: # # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf # noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale) @@ -625,7 +622,7 @@ class SDXLLatentsToLatentsInvocation(BaseInvocation): if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % scheduler.order == 0): progress_bar.update() self.dispatch_progress(context, source_node_id, latents, i, num_inference_steps) - #if callback is not None and i % callback_steps == 0: + # if callback is not None and i % callback_steps == 0: # callback(i, t, latents) else: negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.to(device=unet.device, dtype=unet.dtype) @@ -639,13 +636,13 @@ class SDXLLatentsToLatentsInvocation(BaseInvocation): with tqdm(total=num_inference_steps) as progress_bar: for i, t in enumerate(timesteps): # expand the latents if we are doing classifier free guidance - #latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents + # latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents latent_model_input = scheduler.scale_model_input(latents, t) - #import gc - #gc.collect() - #torch.cuda.empty_cache() + # import gc + # gc.collect() + # torch.cuda.empty_cache() # predict the noise residual @@ -672,38 +669,36 @@ class SDXLLatentsToLatentsInvocation(BaseInvocation): # perform guidance noise_pred = noise_pred_uncond + self.cfg_scale * (noise_pred_text - noise_pred_uncond) - #del noise_pred_text - #del noise_pred_uncond - #import gc - #gc.collect() - #torch.cuda.empty_cache() + # del noise_pred_text + # del noise_pred_uncond + # import gc + # gc.collect() + # torch.cuda.empty_cache() - #if do_classifier_free_guidance and guidance_rescale > 0.0: + # if do_classifier_free_guidance and guidance_rescale > 0.0: # # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf # noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale) # compute the previous noisy sample x_t -> x_t-1 latents = scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0] - #del noise_pred - #import gc - #gc.collect() - #torch.cuda.empty_cache() + # del noise_pred + # import gc + # gc.collect() + # torch.cuda.empty_cache() # call the callback, if provided if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % scheduler.order == 0): progress_bar.update() self.dispatch_progress(context, source_node_id, latents, i, num_inference_steps) - #if callback is not None and i % callback_steps == 0: + # if callback is not None and i % callback_steps == 0: # callback(i, t, latents) - - ################# latents = latents.to("cpu") torch.cuda.empty_cache() - name = f'{context.graph_execution_state_id}__{self.id}' + name = f"{context.graph_execution_state_id}__{self.id}" context.services.latents.save(name, latents) return build_latents_output(latents_name=name, latents=latents) diff --git a/invokeai/app/invocations/upscale.py b/invokeai/app/invocations/upscale.py index 1a45a631df..fd220223db 100644 --- a/invokeai/app/invocations/upscale.py +++ b/invokeai/app/invocations/upscale.py @@ -29,16 +29,11 @@ class ESRGANInvocation(BaseInvocation): type: Literal["esrgan"] = "esrgan" image: Union[ImageField, None] = Field(default=None, description="The input image") - model_name: ESRGAN_MODELS = Field( - default="RealESRGAN_x4plus.pth", description="The Real-ESRGAN model to use" - ) + model_name: ESRGAN_MODELS = Field(default="RealESRGAN_x4plus.pth", description="The Real-ESRGAN model to use") class Config(InvocationConfig): schema_extra = { - "ui": { - "title": "Upscale (RealESRGAN)", - "tags": ["image", "upscale", "realesrgan"] - }, + "ui": {"title": "Upscale (RealESRGAN)", "tags": ["image", "upscale", "realesrgan"]}, } def invoke(self, context: InvocationContext) -> ImageOutput: @@ -108,9 +103,7 @@ class ESRGANInvocation(BaseInvocation): upscaled_image, img_mode = upsampler.enhance(cv_image) # back to PIL - pil_image = Image.fromarray( - cv.cvtColor(upscaled_image, cv.COLOR_BGR2RGB) - ).convert("RGBA") + pil_image = Image.fromarray(cv.cvtColor(upscaled_image, cv.COLOR_BGR2RGB)).convert("RGBA") image_dto = context.services.images.create( image=pil_image, diff --git a/invokeai/app/models/exceptions.py b/invokeai/app/models/exceptions.py index 32ad3b8f03..662e1948ce 100644 --- a/invokeai/app/models/exceptions.py +++ b/invokeai/app/models/exceptions.py @@ -1,3 +1,4 @@ class CanceledException(Exception): """Execution canceled by user.""" + pass diff --git a/invokeai/app/models/image.py b/invokeai/app/models/image.py index 1183cabc54..2a5a0f9d3b 100644 --- a/invokeai/app/models/image.py +++ b/invokeai/app/models/image.py @@ -8,6 +8,7 @@ from ..invocations.baseinvocation import ( InvocationConfig, ) + class ImageField(BaseModel): """An image field used for passing image objects between invocations""" @@ -34,6 +35,7 @@ class ProgressImage(BaseModel): height: int = Field(description="The effective height of the image in pixels") dataURL: str = Field(description="The image data as a b64 data URL") + class PILInvocationConfig(BaseModel): """Helper class to provide all PIL invocations with additional config""" @@ -44,6 +46,7 @@ class PILInvocationConfig(BaseModel): }, } + class ImageOutput(BaseInvocationOutput): """Base class for invocations that output an image""" @@ -76,6 +79,7 @@ class MaskOutput(BaseInvocationOutput): ] } + class ResourceOrigin(str, Enum, metaclass=MetaEnum): """The origin of a resource (eg image). @@ -132,5 +136,3 @@ class InvalidImageCategoryException(ValueError): def __init__(self, message="Invalid image category."): super().__init__(message) - - diff --git a/invokeai/app/services/board_image_record_storage.py b/invokeai/app/services/board_image_record_storage.py index 491972bd32..f0007c8cef 100644 --- a/invokeai/app/services/board_image_record_storage.py +++ b/invokeai/app/services/board_image_record_storage.py @@ -207,9 +207,7 @@ class SqliteBoardImageRecordStorage(BoardImageRecordStorageBase): raise e finally: self._lock.release() - return OffsetPaginatedResults( - items=images, offset=offset, limit=limit, total=count - ) + return OffsetPaginatedResults(items=images, offset=offset, limit=limit, total=count) def get_all_board_image_names_for_board(self, board_id: str) -> list[str]: try: diff --git a/invokeai/app/services/board_images.py b/invokeai/app/services/board_images.py index b9f9663603..22332d6c29 100644 --- a/invokeai/app/services/board_images.py +++ b/invokeai/app/services/board_images.py @@ -102,9 +102,7 @@ class BoardImagesService(BoardImagesServiceABC): self, board_id: str, ) -> list[str]: - return self._services.board_image_records.get_all_board_image_names_for_board( - board_id - ) + return self._services.board_image_records.get_all_board_image_names_for_board(board_id) def get_board_for_image( self, @@ -114,9 +112,7 @@ class BoardImagesService(BoardImagesServiceABC): return board_id -def board_record_to_dto( - board_record: BoardRecord, cover_image_name: Optional[str], image_count: int -) -> BoardDTO: +def board_record_to_dto(board_record: BoardRecord, cover_image_name: Optional[str], image_count: int) -> BoardDTO: """Converts a board record to a board DTO.""" return BoardDTO( **board_record.dict(exclude={"cover_image_name"}), diff --git a/invokeai/app/services/board_record_storage.py b/invokeai/app/services/board_record_storage.py index 15ea9cc5a7..2fad7b0ab3 100644 --- a/invokeai/app/services/board_record_storage.py +++ b/invokeai/app/services/board_record_storage.py @@ -15,9 +15,7 @@ from pydantic import BaseModel, Field, Extra class BoardChanges(BaseModel, extra=Extra.forbid): board_name: Optional[str] = Field(description="The board's new name.") - cover_image_name: Optional[str] = Field( - description="The name of the board's new cover image." - ) + cover_image_name: Optional[str] = Field(description="The name of the board's new cover image.") class BoardRecordNotFoundException(Exception): @@ -292,9 +290,7 @@ class SqliteBoardRecordStorage(BoardRecordStorageBase): count = cast(int, self._cursor.fetchone()[0]) - return OffsetPaginatedResults[BoardRecord]( - items=boards, offset=offset, limit=limit, total=count - ) + return OffsetPaginatedResults[BoardRecord](items=boards, offset=offset, limit=limit, total=count) except sqlite3.Error as e: self._conn.rollback() diff --git a/invokeai/app/services/boards.py b/invokeai/app/services/boards.py index 9361322e6c..53d30b2e85 100644 --- a/invokeai/app/services/boards.py +++ b/invokeai/app/services/boards.py @@ -108,16 +108,12 @@ class BoardService(BoardServiceABC): def get_dto(self, board_id: str) -> BoardDTO: board_record = self._services.board_records.get(board_id) - cover_image = self._services.image_records.get_most_recent_image_for_board( - board_record.board_id - ) + cover_image = self._services.image_records.get_most_recent_image_for_board(board_record.board_id) if cover_image: cover_image_name = cover_image.image_name else: cover_image_name = None - image_count = self._services.board_image_records.get_image_count_for_board( - board_id - ) + image_count = self._services.board_image_records.get_image_count_for_board(board_id) return board_record_to_dto(board_record, cover_image_name, image_count) def update( @@ -126,60 +122,44 @@ class BoardService(BoardServiceABC): changes: BoardChanges, ) -> BoardDTO: board_record = self._services.board_records.update(board_id, changes) - cover_image = self._services.image_records.get_most_recent_image_for_board( - board_record.board_id - ) + cover_image = self._services.image_records.get_most_recent_image_for_board(board_record.board_id) if cover_image: cover_image_name = cover_image.image_name else: cover_image_name = None - image_count = self._services.board_image_records.get_image_count_for_board( - board_id - ) + image_count = self._services.board_image_records.get_image_count_for_board(board_id) return board_record_to_dto(board_record, cover_image_name, image_count) def delete(self, board_id: str) -> None: self._services.board_records.delete(board_id) - def get_many( - self, offset: int = 0, limit: int = 10 - ) -> OffsetPaginatedResults[BoardDTO]: + def get_many(self, offset: int = 0, limit: int = 10) -> OffsetPaginatedResults[BoardDTO]: board_records = self._services.board_records.get_many(offset, limit) board_dtos = [] for r in board_records.items: - cover_image = self._services.image_records.get_most_recent_image_for_board( - r.board_id - ) + cover_image = self._services.image_records.get_most_recent_image_for_board(r.board_id) if cover_image: cover_image_name = cover_image.image_name else: cover_image_name = None - image_count = self._services.board_image_records.get_image_count_for_board( - r.board_id - ) + image_count = self._services.board_image_records.get_image_count_for_board(r.board_id) board_dtos.append(board_record_to_dto(r, cover_image_name, image_count)) - return OffsetPaginatedResults[BoardDTO]( - items=board_dtos, offset=offset, limit=limit, total=len(board_dtos) - ) + return OffsetPaginatedResults[BoardDTO](items=board_dtos, offset=offset, limit=limit, total=len(board_dtos)) def get_all(self) -> list[BoardDTO]: board_records = self._services.board_records.get_all() board_dtos = [] for r in board_records: - cover_image = self._services.image_records.get_most_recent_image_for_board( - r.board_id - ) + cover_image = self._services.image_records.get_most_recent_image_for_board(r.board_id) if cover_image: cover_image_name = cover_image.image_name else: cover_image_name = None - image_count = self._services.board_image_records.get_image_count_for_board( - r.board_id - ) + image_count = self._services.board_image_records.get_image_count_for_board(r.board_id) board_dtos.append(board_record_to_dto(r, cover_image_name, image_count)) - return board_dtos \ No newline at end of file + return board_dtos diff --git a/invokeai/app/services/config.py b/invokeai/app/services/config.py index dfcff86ca0..98855fe879 100644 --- a/invokeai/app/services/config.py +++ b/invokeai/app/services/config.py @@ -1,6 +1,6 @@ # Copyright (c) 2023 Lincoln Stein (https://github.com/lstein) and the InvokeAI Development Team -'''Invokeai configuration system. +"""Invokeai configuration system. Arguments and fields are taken from the pydantic definition of the model. Defaults can be set by creating a yaml configuration file that @@ -158,7 +158,7 @@ two configs are kept in separate sections of the config file: outdir: outputs ... -''' +""" from __future__ import annotations import argparse import pydoc @@ -170,64 +170,68 @@ from pathlib import Path from pydantic import BaseSettings, Field, parse_obj_as from typing import ClassVar, Dict, List, Set, Literal, Union, get_origin, get_type_hints, get_args -INIT_FILE = Path('invokeai.yaml') -MODEL_CORE = Path('models/core') -DB_FILE = Path('invokeai.db') -LEGACY_INIT_FILE = Path('invokeai.init') +INIT_FILE = Path("invokeai.yaml") +MODEL_CORE = Path("models/core") +DB_FILE = Path("invokeai.db") +LEGACY_INIT_FILE = Path("invokeai.init") + class InvokeAISettings(BaseSettings): - ''' + """ Runtime configuration settings in which default values are read from an omegaconf .yaml file. - ''' - initconf : ClassVar[DictConfig] = None - argparse_groups : ClassVar[Dict] = {} + """ - def parse_args(self, argv: list=sys.argv[1:]): + initconf: ClassVar[DictConfig] = None + argparse_groups: ClassVar[Dict] = {} + + def parse_args(self, argv: list = sys.argv[1:]): parser = self.get_parser() opt = parser.parse_args(argv) for name in self.__fields__: if name not in self._excluded(): - setattr(self, name, getattr(opt,name)) + setattr(self, name, getattr(opt, name)) - def to_yaml(self)->str: + def to_yaml(self) -> str: """ Return a YAML string representing our settings. This can be used as the contents of `invokeai.yaml` to restore settings later. """ cls = self.__class__ - type = get_args(get_type_hints(cls)['type'])[0] - field_dict = dict({type:dict()}) - for name,field in self.__fields__.items(): + type = get_args(get_type_hints(cls)["type"])[0] + field_dict = dict({type: dict()}) + for name, field in self.__fields__.items(): if name in cls._excluded_from_yaml(): continue category = field.field_info.extra.get("category") or "Uncategorized" - value = getattr(self,name) + value = getattr(self, name) if category not in field_dict[type]: field_dict[type][category] = dict() # keep paths as strings to make it easier to read - field_dict[type][category][name] = str(value) if isinstance(value,Path) else value + field_dict[type][category][name] = str(value) if isinstance(value, Path) else value conf = OmegaConf.create(field_dict) return OmegaConf.to_yaml(conf) @classmethod def add_parser_arguments(cls, parser): - if 'type' in get_type_hints(cls): - settings_stanza = get_args(get_type_hints(cls)['type'])[0] + if "type" in get_type_hints(cls): + settings_stanza = get_args(get_type_hints(cls)["type"])[0] else: settings_stanza = "Uncategorized" - env_prefix = cls.Config.env_prefix if hasattr(cls.Config,'env_prefix') else settings_stanza.upper() + env_prefix = cls.Config.env_prefix if hasattr(cls.Config, "env_prefix") else settings_stanza.upper() - initconf = cls.initconf.get(settings_stanza) \ - if cls.initconf and settings_stanza in cls.initconf \ - else OmegaConf.create() + initconf = ( + cls.initconf.get(settings_stanza) + if cls.initconf and settings_stanza in cls.initconf + else OmegaConf.create() + ) # create an upcase version of the environment in # order to achieve case-insensitive environment # variables (the way Windows does) upcase_environ = dict() - for key,value in os.environ.items(): + for key, value in os.environ.items(): upcase_environ[key.upper()] = value fields = cls.__fields__ @@ -237,8 +241,8 @@ class InvokeAISettings(BaseSettings): if name not in cls._excluded(): current_default = field.default - category = field.field_info.extra.get("category","Uncategorized") - env_name = env_prefix + '_' + name + category = field.field_info.extra.get("category", "Uncategorized") + env_name = env_prefix + "_" + name if category in initconf and name in initconf.get(category): field.default = initconf.get(category).get(name) if env_name.upper() in upcase_environ: @@ -248,15 +252,15 @@ class InvokeAISettings(BaseSettings): field.default = current_default @classmethod - def cmd_name(self, command_field: str='type')->str: + def cmd_name(self, command_field: str = "type") -> str: hints = get_type_hints(self) if command_field in hints: return get_args(hints[command_field])[0] else: - return 'Uncategorized' + return "Uncategorized" @classmethod - def get_parser(cls)->ArgumentParser: + def get_parser(cls) -> ArgumentParser: parser = PagingArgumentParser( prog=cls.cmd_name(), description=cls.__doc__, @@ -269,24 +273,41 @@ class InvokeAISettings(BaseSettings): parser.add_parser(cls.cmd_name(), help=cls.__doc__) @classmethod - def _excluded(self)->List[str]: + def _excluded(self) -> List[str]: # internal fields that shouldn't be exposed as command line options - return ['type','initconf'] - + return ["type", "initconf"] + @classmethod - def _excluded_from_yaml(self)->List[str]: + def _excluded_from_yaml(self) -> List[str]: # combination of deprecated parameters and internal ones that shouldn't be exposed as invokeai.yaml options - return ['type','initconf', 'gpu_mem_reserved', 'max_loaded_models', 'version', 'from_file', 'model', 'restore', 'root', 'nsfw_checker'] + return [ + "type", + "initconf", + "gpu_mem_reserved", + "max_loaded_models", + "version", + "from_file", + "model", + "restore", + "root", + "nsfw_checker", + ] class Config: - env_file_encoding = 'utf-8' + env_file_encoding = "utf-8" arbitrary_types_allowed = True case_sensitive = True @classmethod - def add_field_argument(cls, command_parser, name: str, field, default_override = None): + def add_field_argument(cls, command_parser, name: str, field, default_override=None): field_type = get_type_hints(cls).get(name) - default = default_override if default_override is not None else field.default if field.default_factory is None else field.default_factory() + default = ( + default_override + if default_override is not None + else field.default + if field.default_factory is None + else field.default_factory() + ) if category := field.field_info.extra.get("category"): if category not in cls.argparse_groups: cls.argparse_groups[category] = command_parser.add_argument_group(category) @@ -315,10 +336,10 @@ class InvokeAISettings(BaseSettings): argparse_group.add_argument( f"--{name}", dest=name, - nargs='*', + nargs="*", type=field.type_, default=default, - action=argparse.BooleanOptionalAction if field.type_==bool else 'store', + action=argparse.BooleanOptionalAction if field.type_ == bool else "store", help=field.field_info.description, ) else: @@ -327,31 +348,35 @@ class InvokeAISettings(BaseSettings): dest=name, type=field.type_, default=default, - action=argparse.BooleanOptionalAction if field.type_==bool else 'store', + action=argparse.BooleanOptionalAction if field.type_ == bool else "store", help=field.field_info.description, ) -def _find_root()->Path: + + +def _find_root() -> Path: venv = Path(os.environ.get("VIRTUAL_ENV") or ".") if os.environ.get("INVOKEAI_ROOT"): root = Path(os.environ.get("INVOKEAI_ROOT")).resolve() - elif any([(venv.parent/x).exists() for x in [INIT_FILE, LEGACY_INIT_FILE, MODEL_CORE]]): + elif any([(venv.parent / x).exists() for x in [INIT_FILE, LEGACY_INIT_FILE, MODEL_CORE]]): root = (venv.parent).resolve() else: root = Path("~/invokeai").expanduser().resolve() return root + class InvokeAIAppConfig(InvokeAISettings): - ''' -Generate images using Stable Diffusion. Use "invokeai" to launch -the command-line client (recommended for experts only), or -"invokeai-web" to launch the web server. Global options -can be changed by editing the file "INVOKEAI_ROOT/invokeai.yaml" or by -setting environment variables INVOKEAI_. - ''' + """ + Generate images using Stable Diffusion. Use "invokeai" to launch + the command-line client (recommended for experts only), or + "invokeai-web" to launch the web server. Global options + can be changed by editing the file "INVOKEAI_ROOT/invokeai.yaml" or by + setting environment variables INVOKEAI_. + """ + singleton_config: ClassVar[InvokeAIAppConfig] = None singleton_init: ClassVar[Dict] = None - #fmt: off + # fmt: off type: Literal["InvokeAI"] = "InvokeAI" host : str = Field(default="127.0.0.1", description="IP address to bind to", category='Web Server') port : int = Field(default=9090, description="Port to bind to", category='Web Server') @@ -399,16 +424,16 @@ setting environment variables INVOKEAI_. log_level : Literal[tuple(["debug","info","warning","error","critical"])] = Field(default="info", description="Emit logging messages at this level or higher", category="Logging") version : bool = Field(default=False, description="Show InvokeAI version and exit", category="Other") - #fmt: on + # fmt: on - def parse_args(self, argv: List[str]=None, conf: DictConfig = None, clobber=False): - ''' + def parse_args(self, argv: List[str] = None, conf: DictConfig = None, clobber=False): + """ Update settings with contents of init file, environment, and command-line settings. :param conf: alternate Omegaconf dictionary object :param argv: aternate sys.argv list :param clobber: ovewrite any initialization parameters passed during initialization - ''' + """ # Set the runtime root directory. We parse command-line switches here # in order to pick up the --root_dir option. super().parse_args(argv) @@ -425,135 +450,139 @@ setting environment variables INVOKEAI_. if self.singleton_init and not clobber: hints = get_type_hints(self.__class__) for k in self.singleton_init: - setattr(self,k,parse_obj_as(hints[k],self.singleton_init[k])) + setattr(self, k, parse_obj_as(hints[k], self.singleton_init[k])) @classmethod - def get_config(cls,**kwargs)->InvokeAIAppConfig: - ''' + def get_config(cls, **kwargs) -> InvokeAIAppConfig: + """ This returns a singleton InvokeAIAppConfig configuration object. - ''' - if cls.singleton_config is None \ - or type(cls.singleton_config)!=cls \ - or (kwargs and cls.singleton_init != kwargs): + """ + if ( + cls.singleton_config is None + or type(cls.singleton_config) != cls + or (kwargs and cls.singleton_init != kwargs) + ): cls.singleton_config = cls(**kwargs) cls.singleton_init = kwargs return cls.singleton_config @property - def root_path(self)->Path: - ''' + def root_path(self) -> Path: + """ Path to the runtime root directory - ''' + """ if self.root: return Path(self.root).expanduser().absolute() else: return self.find_root() @property - def root_dir(self)->Path: - ''' + def root_dir(self) -> Path: + """ Alias for above. - ''' + """ return self.root_path - def _resolve(self,partial_path:Path)->Path: + def _resolve(self, partial_path: Path) -> Path: return (self.root_path / partial_path).resolve() @property - def init_file_path(self)->Path: - ''' + def init_file_path(self) -> Path: + """ Path to invokeai.yaml - ''' + """ return self._resolve(INIT_FILE) @property - def output_path(self)->Path: - ''' + def output_path(self) -> Path: + """ Path to defaults outputs directory. - ''' + """ return self._resolve(self.outdir) @property - def db_path(self)->Path: - ''' + def db_path(self) -> Path: + """ Path to the invokeai.db file. - ''' + """ return self._resolve(self.db_dir) / DB_FILE @property - def model_conf_path(self)->Path: - ''' + def model_conf_path(self) -> Path: + """ Path to models configuration file. - ''' + """ return self._resolve(self.conf_path) @property - def legacy_conf_path(self)->Path: - ''' + def legacy_conf_path(self) -> Path: + """ Path to directory of legacy configuration files (e.g. v1-inference.yaml) - ''' + """ return self._resolve(self.legacy_conf_dir) @property - def models_path(self)->Path: - ''' + def models_path(self) -> Path: + """ Path to the models directory - ''' + """ return self._resolve(self.models_dir) @property - def autoconvert_path(self)->Path: - ''' + def autoconvert_path(self) -> Path: + """ Path to the directory containing models to be imported automatically at startup. - ''' + """ return self._resolve(self.autoconvert_dir) if self.autoconvert_dir else None # the following methods support legacy calls leftover from the Globals era @property - def full_precision(self)->bool: + def full_precision(self) -> bool: """Return true if precision set to float32""" - return self.precision=='float32' + return self.precision == "float32" @property - def disable_xformers(self)->bool: + def disable_xformers(self) -> bool: """Return true if xformers_enabled is false""" return not self.xformers_enabled @property - def try_patchmatch(self)->bool: + def try_patchmatch(self) -> bool: """Return true if patchmatch true""" return self.patchmatch @property - def nsfw_checker(self)->bool: - """ NSFW node is always active and disabled from Web UIe""" + def nsfw_checker(self) -> bool: + """NSFW node is always active and disabled from Web UIe""" return True @property - def invisible_watermark(self)->bool: - """ invisible watermark node is always active and disabled from Web UIe""" + def invisible_watermark(self) -> bool: + """invisible watermark node is always active and disabled from Web UIe""" return True - + @staticmethod - def find_root()->Path: - ''' + def find_root() -> Path: + """ Choose the runtime root directory when not specified on command line or init file. - ''' + """ return _find_root() class PagingArgumentParser(argparse.ArgumentParser): - ''' + """ A custom ArgumentParser that uses pydoc to page its output. It also supports reading defaults from an init file. - ''' + """ + def print_help(self, file=None): text = self.format_help() pydoc.pager(text) -def get_invokeai_config(**kwargs)->InvokeAIAppConfig: - ''' + +def get_invokeai_config(**kwargs) -> InvokeAIAppConfig: + """ Legacy function which returns InvokeAIAppConfig.get_config() - ''' + """ return InvokeAIAppConfig.get_config(**kwargs) diff --git a/invokeai/app/services/default_graphs.py b/invokeai/app/services/default_graphs.py index 22e35d1d6b..cafb6f0339 100644 --- a/invokeai/app/services/default_graphs.py +++ b/invokeai/app/services/default_graphs.py @@ -7,57 +7,80 @@ from .graph import Edge, EdgeConnection, ExposedNodeInput, ExposedNodeOutput, Gr from .item_storage import ItemStorageABC -default_text_to_image_graph_id = '539b2af5-2b4d-4d8c-8071-e54a3255fc74' +default_text_to_image_graph_id = "539b2af5-2b4d-4d8c-8071-e54a3255fc74" def create_text_to_image() -> LibraryGraph: return LibraryGraph( id=default_text_to_image_graph_id, - name='t2i', - description='Converts text to an image', + name="t2i", + description="Converts text to an image", graph=Graph( nodes={ - 'width': ParamIntInvocation(id='width', a=512), - 'height': ParamIntInvocation(id='height', a=512), - 'seed': ParamIntInvocation(id='seed', a=-1), - '3': NoiseInvocation(id='3'), - '4': CompelInvocation(id='4'), - '5': CompelInvocation(id='5'), - '6': TextToLatentsInvocation(id='6'), - '7': LatentsToImageInvocation(id='7'), - '8': ImageNSFWBlurInvocation(id='8'), + "width": ParamIntInvocation(id="width", a=512), + "height": ParamIntInvocation(id="height", a=512), + "seed": ParamIntInvocation(id="seed", a=-1), + "3": NoiseInvocation(id="3"), + "4": CompelInvocation(id="4"), + "5": CompelInvocation(id="5"), + "6": TextToLatentsInvocation(id="6"), + "7": LatentsToImageInvocation(id="7"), + "8": ImageNSFWBlurInvocation(id="8"), }, edges=[ - Edge(source=EdgeConnection(node_id='width', field='a'), destination=EdgeConnection(node_id='3', field='width')), - Edge(source=EdgeConnection(node_id='height', field='a'), destination=EdgeConnection(node_id='3', field='height')), - Edge(source=EdgeConnection(node_id='seed', field='a'), destination=EdgeConnection(node_id='3', field='seed')), - Edge(source=EdgeConnection(node_id='3', field='noise'), destination=EdgeConnection(node_id='6', field='noise')), - Edge(source=EdgeConnection(node_id='6', field='latents'), destination=EdgeConnection(node_id='7', field='latents')), - Edge(source=EdgeConnection(node_id='4', field='conditioning'), destination=EdgeConnection(node_id='6', field='positive_conditioning')), - Edge(source=EdgeConnection(node_id='5', field='conditioning'), destination=EdgeConnection(node_id='6', field='negative_conditioning')), - Edge(source=EdgeConnection(node_id='7', field='image'), destination=EdgeConnection(node_id='8', field='image')), - ] + Edge( + source=EdgeConnection(node_id="width", field="a"), + destination=EdgeConnection(node_id="3", field="width"), + ), + Edge( + source=EdgeConnection(node_id="height", field="a"), + destination=EdgeConnection(node_id="3", field="height"), + ), + Edge( + source=EdgeConnection(node_id="seed", field="a"), + destination=EdgeConnection(node_id="3", field="seed"), + ), + Edge( + source=EdgeConnection(node_id="3", field="noise"), + destination=EdgeConnection(node_id="6", field="noise"), + ), + Edge( + source=EdgeConnection(node_id="6", field="latents"), + destination=EdgeConnection(node_id="7", field="latents"), + ), + Edge( + source=EdgeConnection(node_id="4", field="conditioning"), + destination=EdgeConnection(node_id="6", field="positive_conditioning"), + ), + Edge( + source=EdgeConnection(node_id="5", field="conditioning"), + destination=EdgeConnection(node_id="6", field="negative_conditioning"), + ), + Edge( + source=EdgeConnection(node_id="7", field="image"), + destination=EdgeConnection(node_id="8", field="image"), + ), + ], ), exposed_inputs=[ - ExposedNodeInput(node_path='4', field='prompt', alias='positive_prompt'), - ExposedNodeInput(node_path='5', field='prompt', alias='negative_prompt'), - ExposedNodeInput(node_path='width', field='a', alias='width'), - ExposedNodeInput(node_path='height', field='a', alias='height'), - ExposedNodeInput(node_path='seed', field='a', alias='seed'), + ExposedNodeInput(node_path="4", field="prompt", alias="positive_prompt"), + ExposedNodeInput(node_path="5", field="prompt", alias="negative_prompt"), + ExposedNodeInput(node_path="width", field="a", alias="width"), + ExposedNodeInput(node_path="height", field="a", alias="height"), + ExposedNodeInput(node_path="seed", field="a", alias="seed"), ], - exposed_outputs=[ - ExposedNodeOutput(node_path='8', field='image', alias='image') - ]) + exposed_outputs=[ExposedNodeOutput(node_path="8", field="image", alias="image")], + ) def create_system_graphs(graph_library: ItemStorageABC[LibraryGraph]) -> list[LibraryGraph]: """Creates the default system graphs, or adds new versions if the old ones don't match""" - + # TODO: Uncomment this when we are ready to fix this up to prevent breaking changes graphs: list[LibraryGraph] = list() # text_to_image = graph_library.get(default_text_to_image_graph_id) - + # # TODO: Check if the graph is the same as the default one, and if not, update it # #if text_to_image is None: text_to_image = create_text_to_image() diff --git a/invokeai/app/services/events.py b/invokeai/app/services/events.py index 73d74de2d9..30fa89bd29 100644 --- a/invokeai/app/services/events.py +++ b/invokeai/app/services/events.py @@ -44,9 +44,7 @@ class EventServiceBase: graph_execution_state_id=graph_execution_state_id, node=node, source_node_id=source_node_id, - progress_image=progress_image.dict() - if progress_image is not None - else None, + progress_image=progress_image.dict() if progress_image is not None else None, step=step, total_steps=total_steps, ), @@ -90,9 +88,7 @@ class EventServiceBase: ), ) - def emit_invocation_started( - self, graph_execution_state_id: str, node: dict, source_node_id: str - ) -> None: + def emit_invocation_started(self, graph_execution_state_id: str, node: dict, source_node_id: str) -> None: """Emitted when an invocation has started""" self.__emit_session_event( event_name="invocation_started", diff --git a/invokeai/app/services/graph.py b/invokeai/app/services/graph.py index 24096da29b..d7f021df14 100644 --- a/invokeai/app/services/graph.py +++ b/invokeai/app/services/graph.py @@ -28,6 +28,7 @@ from ..invocations.baseinvocation import ( # in 3.10 this would be "from types import NoneType" NoneType = type(None) + class EdgeConnection(BaseModel): node_id: str = Field(description="The id of the node for this edge connection") field: str = Field(description="The field for this connection") @@ -61,6 +62,7 @@ def get_input_field(node: BaseInvocation, field: str) -> Any: node_input_field = node_inputs.get(field) or None return node_input_field + def is_union_subtype(t1, t2): t1_args = get_args(t1) t2_args = get_args(t2) @@ -71,6 +73,7 @@ def is_union_subtype(t1, t2): # t1 is a Union, check that all of its types are in t2_args return all(arg in t2_args for arg in t1_args) + def is_list_or_contains_list(t): t_args = get_args(t) @@ -154,15 +157,17 @@ class GraphInvocationOutput(BaseInvocationOutput): class Config: schema_extra = { - 'required': [ - 'type', - 'image', + "required": [ + "type", + "image", ] } + # TODO: Fill this out and move to invocations class GraphInvocation(BaseInvocation): """Execute a graph""" + type: Literal["graph"] = "graph" # TODO: figure out how to create a default here @@ -182,23 +187,21 @@ class IterateInvocationOutput(BaseInvocationOutput): class Config: schema_extra = { - 'required': [ - 'type', - 'item', + "required": [ + "type", + "item", ] } + # TODO: Fill this out and move to invocations class IterateInvocation(BaseInvocation): """Iterates over a list of items""" + type: Literal["iterate"] = "iterate" - collection: list[Any] = Field( - description="The list of items to iterate over", default_factory=list - ) - index: int = Field( - description="The index, will be provided on executed iterators", default=0 - ) + collection: list[Any] = Field(description="The list of items to iterate over", default_factory=list) + index: int = Field(description="The index, will be provided on executed iterators", default=0) def invoke(self, context: InvocationContext) -> IterateInvocationOutput: """Produces the outputs as values""" @@ -212,12 +215,13 @@ class CollectInvocationOutput(BaseInvocationOutput): class Config: schema_extra = { - 'required': [ - 'type', - 'collection', + "required": [ + "type", + "collection", ] } + class CollectInvocation(BaseInvocation): """Collects values into a collection""" @@ -269,9 +273,7 @@ class Graph(BaseModel): if node_path in self.nodes: return (self, node_path) - node_id = ( - node_path if "." not in node_path else node_path[: node_path.index(".")] - ) + node_id = node_path if "." not in node_path else node_path[: node_path.index(".")] if node_id not in self.nodes: raise NodeNotFoundError(f"Node {node_path} not found in graph") @@ -333,9 +335,7 @@ class Graph(BaseModel): return False # Validate all edges reference nodes in the graph - node_ids = set( - [e.source.node_id for e in self.edges] + [e.destination.node_id for e in self.edges] - ) + node_ids = set([e.source.node_id for e in self.edges] + [e.destination.node_id for e in self.edges]) if not all((self.has_node(node_id) for node_id in node_ids)): return False @@ -361,22 +361,14 @@ class Graph(BaseModel): # Validate all iterators # TODO: may need to validate all iterators in subgraphs so edge connections in parent graphs will be available if not all( - ( - self._is_iterator_connection_valid(n.id) - for n in self.nodes.values() - if isinstance(n, IterateInvocation) - ) + (self._is_iterator_connection_valid(n.id) for n in self.nodes.values() if isinstance(n, IterateInvocation)) ): return False # Validate all collectors # TODO: may need to validate all collectors in subgraphs so edge connections in parent graphs will be available if not all( - ( - self._is_collector_connection_valid(n.id) - for n in self.nodes.values() - if isinstance(n, CollectInvocation) - ) + (self._is_collector_connection_valid(n.id) for n in self.nodes.values() if isinstance(n, CollectInvocation)) ): return False @@ -395,48 +387,51 @@ class Graph(BaseModel): # Validate that an edge to this node+field doesn't already exist input_edges = self._get_input_edges(edge.destination.node_id, edge.destination.field) if len(input_edges) > 0 and not isinstance(to_node, CollectInvocation): - raise InvalidEdgeError(f'Edge to node {edge.destination.node_id} field {edge.destination.field} already exists') + raise InvalidEdgeError( + f"Edge to node {edge.destination.node_id} field {edge.destination.field} already exists" + ) # Validate that no cycles would be created g = self.nx_graph_flat() g.add_edge(edge.source.node_id, edge.destination.node_id) if not nx.is_directed_acyclic_graph(g): - raise InvalidEdgeError(f'Edge creates a cycle in the graph: {edge.source.node_id} -> {edge.destination.node_id}') + raise InvalidEdgeError( + f"Edge creates a cycle in the graph: {edge.source.node_id} -> {edge.destination.node_id}" + ) # Validate that the field types are compatible - if not are_connections_compatible( - from_node, edge.source.field, to_node, edge.destination.field - ): - raise InvalidEdgeError(f'Fields are incompatible: cannot connect {edge.source.node_id}.{edge.source.field} to {edge.destination.node_id}.{edge.destination.field}') + if not are_connections_compatible(from_node, edge.source.field, to_node, edge.destination.field): + raise InvalidEdgeError( + f"Fields are incompatible: cannot connect {edge.source.node_id}.{edge.source.field} to {edge.destination.node_id}.{edge.destination.field}" + ) # Validate if iterator output type matches iterator input type (if this edge results in both being set) if isinstance(to_node, IterateInvocation) and edge.destination.field == "collection": - if not self._is_iterator_connection_valid( - edge.destination.node_id, new_input=edge.source - ): - raise InvalidEdgeError(f'Iterator input type does not match iterator output type: {edge.source.node_id}.{edge.source.field} to {edge.destination.node_id}.{edge.destination.field}') + if not self._is_iterator_connection_valid(edge.destination.node_id, new_input=edge.source): + raise InvalidEdgeError( + f"Iterator input type does not match iterator output type: {edge.source.node_id}.{edge.source.field} to {edge.destination.node_id}.{edge.destination.field}" + ) # Validate if iterator input type matches output type (if this edge results in both being set) if isinstance(from_node, IterateInvocation) and edge.source.field == "item": - if not self._is_iterator_connection_valid( - edge.source.node_id, new_output=edge.destination - ): - raise InvalidEdgeError(f'Iterator output type does not match iterator input type:, {edge.source.node_id}.{edge.source.field} to {edge.destination.node_id}.{edge.destination.field}') + if not self._is_iterator_connection_valid(edge.source.node_id, new_output=edge.destination): + raise InvalidEdgeError( + f"Iterator output type does not match iterator input type:, {edge.source.node_id}.{edge.source.field} to {edge.destination.node_id}.{edge.destination.field}" + ) # Validate if collector input type matches output type (if this edge results in both being set) if isinstance(to_node, CollectInvocation) and edge.destination.field == "item": - if not self._is_collector_connection_valid( - edge.destination.node_id, new_input=edge.source - ): - raise InvalidEdgeError(f'Collector output type does not match collector input type: {edge.source.node_id}.{edge.source.field} to {edge.destination.node_id}.{edge.destination.field}') + if not self._is_collector_connection_valid(edge.destination.node_id, new_input=edge.source): + raise InvalidEdgeError( + f"Collector output type does not match collector input type: {edge.source.node_id}.{edge.source.field} to {edge.destination.node_id}.{edge.destination.field}" + ) # Validate if collector output type matches input type (if this edge results in both being set) if isinstance(from_node, CollectInvocation) and edge.source.field == "collection": - if not self._is_collector_connection_valid( - edge.source.node_id, new_output=edge.destination - ): - raise InvalidEdgeError(f'Collector input type does not match collector output type: {edge.source.node_id}.{edge.source.field} to {edge.destination.node_id}.{edge.destination.field}') - + if not self._is_collector_connection_valid(edge.source.node_id, new_output=edge.destination): + raise InvalidEdgeError( + f"Collector input type does not match collector output type: {edge.source.node_id}.{edge.source.field} to {edge.destination.node_id}.{edge.destination.field}" + ) def has_node(self, node_path: str) -> bool: """Determines whether or not a node exists in the graph.""" @@ -465,17 +460,13 @@ class Graph(BaseModel): # Ensure the node type matches the new node if type(node) != type(new_node): - raise TypeError( - f"Node {node_path} is type {type(node)} but new node is type {type(new_node)}" - ) + raise TypeError(f"Node {node_path} is type {type(node)} but new node is type {type(new_node)}") # Ensure the new id is either the same or is not in the graph prefix = None if "." not in node_path else node_path[: node_path.rindex(".")] new_path = self._get_node_path(new_node.id, prefix=prefix) if new_node.id != node.id and self.has_node(new_path): - raise NodeAlreadyInGraphError( - "Node with id {new_node.id} already exists in graph" - ) + raise NodeAlreadyInGraphError("Node with id {new_node.id} already exists in graph") # Set the new node in the graph graph.nodes[new_node.id] = new_node @@ -497,9 +488,7 @@ class Graph(BaseModel): graph.add_edge( Edge( source=edge.source, - destination=EdgeConnection( - node_id=new_graph_node_path, field=edge.destination.field - ) + destination=EdgeConnection(node_id=new_graph_node_path, field=edge.destination.field), ) ) @@ -512,16 +501,12 @@ class Graph(BaseModel): ) graph.add_edge( Edge( - source=EdgeConnection( - node_id=new_graph_node_path, field=edge.source.field - ), - destination=edge.destination + source=EdgeConnection(node_id=new_graph_node_path, field=edge.source.field), + destination=edge.destination, ) ) - def _get_input_edges( - self, node_path: str, field: Optional[str] = None - ) -> list[Edge]: + def _get_input_edges(self, node_path: str, field: Optional[str] = None) -> list[Edge]: """Gets all input edges for a node""" edges = self._get_input_edges_and_graphs(node_path) @@ -538,7 +523,7 @@ class Graph(BaseModel): destination=EdgeConnection( node_id=self._get_node_path(e.destination.node_id, prefix=prefix), field=e.destination.field, - ) + ), ) for _, prefix, e in filtered_edges ] @@ -550,32 +535,20 @@ class Graph(BaseModel): edges = list() # Return any input edges that appear in this graph - edges.extend( - [(self, prefix, e) for e in self.edges if e.destination.node_id == node_path] - ) + edges.extend([(self, prefix, e) for e in self.edges if e.destination.node_id == node_path]) - node_id = ( - node_path if "." not in node_path else node_path[: node_path.index(".")] - ) + node_id = node_path if "." not in node_path else node_path[: node_path.index(".")] node = self.nodes[node_id] if isinstance(node, GraphInvocation): graph = node.graph - graph_path = ( - node.id - if prefix is None or prefix == "" - else self._get_node_path(node.id, prefix=prefix) - ) - graph_edges = graph._get_input_edges_and_graphs( - node_path[(len(node_id) + 1) :], prefix=graph_path - ) + graph_path = node.id if prefix is None or prefix == "" else self._get_node_path(node.id, prefix=prefix) + graph_edges = graph._get_input_edges_and_graphs(node_path[(len(node_id) + 1) :], prefix=graph_path) edges.extend(graph_edges) return edges - def _get_output_edges( - self, node_path: str, field: str - ) -> list[Edge]: + def _get_output_edges(self, node_path: str, field: str) -> list[Edge]: """Gets all output edges for a node""" edges = self._get_output_edges_and_graphs(node_path) @@ -592,7 +565,7 @@ class Graph(BaseModel): destination=EdgeConnection( node_id=self._get_node_path(e.destination.node_id, prefix=prefix), field=e.destination.field, - ) + ), ) for _, prefix, e in filtered_edges ] @@ -604,25 +577,15 @@ class Graph(BaseModel): edges = list() # Return any input edges that appear in this graph - edges.extend( - [(self, prefix, e) for e in self.edges if e.source.node_id == node_path] - ) + edges.extend([(self, prefix, e) for e in self.edges if e.source.node_id == node_path]) - node_id = ( - node_path if "." not in node_path else node_path[: node_path.index(".")] - ) + node_id = node_path if "." not in node_path else node_path[: node_path.index(".")] node = self.nodes[node_id] if isinstance(node, GraphInvocation): graph = node.graph - graph_path = ( - node.id - if prefix is None or prefix == "" - else self._get_node_path(node.id, prefix=prefix) - ) - graph_edges = graph._get_output_edges_and_graphs( - node_path[(len(node_id) + 1) :], prefix=graph_path - ) + graph_path = node.id if prefix is None or prefix == "" else self._get_node_path(node.id, prefix=prefix) + graph_edges = graph._get_output_edges_and_graphs(node_path[(len(node_id) + 1) :], prefix=graph_path) edges.extend(graph_edges) return edges @@ -646,12 +609,8 @@ class Graph(BaseModel): return False # Get input and output fields (the fields linked to the iterator's input/output) - input_field = get_output_field( - self.get_node(inputs[0].node_id), inputs[0].field - ) - output_fields = list( - [get_input_field(self.get_node(e.node_id), e.field) for e in outputs] - ) + input_field = get_output_field(self.get_node(inputs[0].node_id), inputs[0].field) + output_fields = list([get_input_field(self.get_node(e.node_id), e.field) for e in outputs]) # Input type must be a list if get_origin(input_field) != list: @@ -659,12 +618,7 @@ class Graph(BaseModel): # Validate that all outputs match the input type input_field_item_type = get_args(input_field)[0] - if not all( - ( - are_connection_types_compatible(input_field_item_type, f) - for f in output_fields - ) - ): + if not all((are_connection_types_compatible(input_field_item_type, f) for f in output_fields)): return False return True @@ -684,35 +638,21 @@ class Graph(BaseModel): outputs.append(new_output) # Get input and output fields (the fields linked to the iterator's input/output) - input_fields = list( - [get_output_field(self.get_node(e.node_id), e.field) for e in inputs] - ) - output_fields = list( - [get_input_field(self.get_node(e.node_id), e.field) for e in outputs] - ) + input_fields = list([get_output_field(self.get_node(e.node_id), e.field) for e in inputs]) + output_fields = list([get_input_field(self.get_node(e.node_id), e.field) for e in outputs]) # Validate that all inputs are derived from or match a single type input_field_types = set( [ t for input_field in input_fields - for t in ( - [input_field] - if get_origin(input_field) == None - else get_args(input_field) - ) + for t in ([input_field] if get_origin(input_field) == None else get_args(input_field)) if t != NoneType ] ) # Get unique types type_tree = nx.DiGraph() type_tree.add_nodes_from(input_field_types) - type_tree.add_edges_from( - [ - e - for e in itertools.permutations(input_field_types, 2) - if issubclass(e[1], e[0]) - ] - ) + type_tree.add_edges_from([e for e in itertools.permutations(input_field_types, 2) if issubclass(e[1], e[0])]) type_degrees = type_tree.in_degree(type_tree.nodes) if sum((t[1] == 0 for t in type_degrees)) != 1: # type: ignore return False # There is more than one root type @@ -729,9 +669,7 @@ class Graph(BaseModel): return False # Verify that all outputs match the input type (are a base class or the same class) - if not all( - (issubclass(input_root_type, get_args(f)[0]) for f in output_fields) - ): + if not all((issubclass(input_root_type, get_args(f)[0]) for f in output_fields)): return False return True @@ -751,9 +689,7 @@ class Graph(BaseModel): g.add_edges_from(set([(e.source.node_id, e.destination.node_id) for e in self.edges])) return g - def nx_graph_flat( - self, nx_graph: Optional[nx.DiGraph] = None, prefix: Optional[str] = None - ) -> nx.DiGraph: + def nx_graph_flat(self, nx_graph: Optional[nx.DiGraph] = None, prefix: Optional[str] = None) -> nx.DiGraph: """Returns a flattened NetworkX DiGraph, including all subgraphs (but not with iterations expanded)""" g = nx_graph or nx.DiGraph() @@ -762,26 +698,18 @@ class Graph(BaseModel): [ self._get_node_path(n.id, prefix) for n in self.nodes.values() - if not isinstance(n, GraphInvocation) - and not isinstance(n, IterateInvocation) + if not isinstance(n, GraphInvocation) and not isinstance(n, IterateInvocation) ] ) # Expand graph nodes - for sgn in ( - gn for gn in self.nodes.values() if isinstance(gn, GraphInvocation) - ): + for sgn in (gn for gn in self.nodes.values() if isinstance(gn, GraphInvocation)): g = sgn.graph.nx_graph_flat(g, self._get_node_path(sgn.id, prefix)) # TODO: figure out if iteration nodes need to be expanded unique_edges = set([(e.source.node_id, e.destination.node_id) for e in self.edges]) - g.add_edges_from( - [ - (self._get_node_path(e[0], prefix), self._get_node_path(e[1], prefix)) - for e in unique_edges - ] - ) + g.add_edges_from([(self._get_node_path(e[0], prefix), self._get_node_path(e[1], prefix)) for e in unique_edges]) return g @@ -800,23 +728,19 @@ class GraphExecutionState(BaseModel): ) # Nodes that have been executed - executed: set[str] = Field( - description="The set of node ids that have been executed", default_factory=set - ) + executed: set[str] = Field(description="The set of node ids that have been executed", default_factory=set) executed_history: list[str] = Field( description="The list of node ids that have been executed, in order of execution", default_factory=list, ) # The results of executed nodes - results: dict[ - str, Annotated[InvocationOutputsUnion, Field(discriminator="type")] - ] = Field(description="The results of node executions", default_factory=dict) + results: dict[str, Annotated[InvocationOutputsUnion, Field(discriminator="type")]] = Field( + description="The results of node executions", default_factory=dict + ) # Errors raised when executing nodes - errors: dict[str, str] = Field( - description="Errors raised when executing nodes", default_factory=dict - ) + errors: dict[str, str] = Field(description="Errors raised when executing nodes", default_factory=dict) # Map of prepared/executed nodes to their original nodes prepared_source_mapping: dict[str, str] = Field( @@ -832,16 +756,16 @@ class GraphExecutionState(BaseModel): class Config: schema_extra = { - 'required': [ - 'id', - 'graph', - 'execution_graph', - 'executed', - 'executed_history', - 'results', - 'errors', - 'prepared_source_mapping', - 'source_prepared_mapping', + "required": [ + "id", + "graph", + "execution_graph", + "executed", + "executed_history", + "results", + "errors", + "prepared_source_mapping", + "source_prepared_mapping", ] } @@ -899,9 +823,7 @@ class GraphExecutionState(BaseModel): """Returns true if the graph has any errors""" return len(self.errors) > 0 - def _create_execution_node( - self, node_path: str, iteration_node_map: list[tuple[str, str]] - ) -> list[str]: + def _create_execution_node(self, node_path: str, iteration_node_map: list[tuple[str, str]]) -> list[str]: """Prepares an iteration node and connects all edges, returning the new node id""" node = self.graph.get_node(node_path) @@ -911,20 +833,12 @@ class GraphExecutionState(BaseModel): # If this is an iterator node, we must create a copy for each iteration if isinstance(node, IterateInvocation): # Get input collection edge (should error if there are no inputs) - input_collection_edge = next( - iter(self.graph._get_input_edges(node_path, "collection")) - ) + input_collection_edge = next(iter(self.graph._get_input_edges(node_path, "collection"))) input_collection_prepared_node_id = next( - n[1] - for n in iteration_node_map - if n[0] == input_collection_edge.source.node_id - ) - input_collection_prepared_node_output = self.results[ - input_collection_prepared_node_id - ] - input_collection = getattr( - input_collection_prepared_node_output, input_collection_edge.source.field + n[1] for n in iteration_node_map if n[0] == input_collection_edge.source.node_id ) + input_collection_prepared_node_output = self.results[input_collection_prepared_node_id] + input_collection = getattr(input_collection_prepared_node_output, input_collection_edge.source.field) self_iteration_count = len(input_collection) new_nodes = list() @@ -939,9 +853,7 @@ class GraphExecutionState(BaseModel): # For collect nodes, this may contain multiple inputs to the same field new_edges = list() for edge in input_edges: - for input_node_id in ( - n[1] for n in iteration_node_map if n[0] == edge.source.node_id - ): + for input_node_id in (n[1] for n in iteration_node_map if n[0] == edge.source.node_id): new_edge = Edge( source=EdgeConnection(node_id=input_node_id, field=edge.source.field), destination=EdgeConnection(node_id="", field=edge.destination.field), @@ -982,11 +894,7 @@ class GraphExecutionState(BaseModel): def _iterator_graph(self) -> nx.DiGraph: """Gets a DiGraph with edges to collectors removed so an ancestor search produces all active iterators for any node""" g = self.graph.nx_graph_flat() - collectors = ( - n - for n in self.graph.nodes - if isinstance(self.graph.get_node(n), CollectInvocation) - ) + collectors = (n for n in self.graph.nodes if isinstance(self.graph.get_node(n), CollectInvocation)) for c in collectors: g.remove_edges_from(list(g.in_edges(c))) return g @@ -994,11 +902,7 @@ class GraphExecutionState(BaseModel): def _get_node_iterators(self, node_id: str) -> list[str]: """Gets iterators for a node""" g = self._iterator_graph() - iterators = [ - n - for n in nx.ancestors(g, node_id) - if isinstance(self.graph.get_node(n), IterateInvocation) - ] + iterators = [n for n in nx.ancestors(g, node_id) if isinstance(self.graph.get_node(n), IterateInvocation)] return iterators def _prepare(self) -> Optional[str]: @@ -1045,29 +949,18 @@ class GraphExecutionState(BaseModel): if isinstance(next_node, CollectInvocation): # Collapse all iterator input mappings and create a single execution node for the collect invocation all_iteration_mappings = list( - itertools.chain( - *( - ((s, p) for p in self.source_prepared_mapping[s]) - for s in next_node_parents - ) - ) + itertools.chain(*(((s, p) for p in self.source_prepared_mapping[s]) for s in next_node_parents)) ) # all_iteration_mappings = list(set(itertools.chain(*prepared_parent_mappings))) - create_results = self._create_execution_node( - next_node_id, all_iteration_mappings - ) + create_results = self._create_execution_node(next_node_id, all_iteration_mappings) if create_results is not None: new_node_ids.extend(create_results) else: # Iterators or normal nodes # Get all iterator combinations for this node # Will produce a list of lists of prepared iterator nodes, from which results can be iterated iterator_nodes = self._get_node_iterators(next_node_id) - iterator_nodes_prepared = [ - list(self.source_prepared_mapping[n]) for n in iterator_nodes - ] - iterator_node_prepared_combinations = list( - itertools.product(*iterator_nodes_prepared) - ) + iterator_nodes_prepared = [list(self.source_prepared_mapping[n]) for n in iterator_nodes] + iterator_node_prepared_combinations = list(itertools.product(*iterator_nodes_prepared)) # Select the correct prepared parents for each iteration # For every iterator, the parent must either not be a child of that iterator, or must match the prepared iteration for that iterator @@ -1096,31 +989,16 @@ class GraphExecutionState(BaseModel): return next(iter(prepared_nodes)) # Check if the requested node is an iterator - prepared_iterator = next( - (n for n in prepared_nodes if n in prepared_iterator_nodes), None - ) + prepared_iterator = next((n for n in prepared_nodes if n in prepared_iterator_nodes), None) if prepared_iterator is not None: return prepared_iterator # Filter to only iterator nodes that are a parent of the specified node, in tuple format (prepared, source) - iterator_source_node_mapping = [ - (n, self.prepared_source_mapping[n]) for n in prepared_iterator_nodes - ] - parent_iterators = [ - itn - for itn in iterator_source_node_mapping - if nx.has_path(graph, itn[1], source_node_path) - ] + iterator_source_node_mapping = [(n, self.prepared_source_mapping[n]) for n in prepared_iterator_nodes] + parent_iterators = [itn for itn in iterator_source_node_mapping if nx.has_path(graph, itn[1], source_node_path)] return next( - ( - n - for n in prepared_nodes - if all( - nx.has_path(execution_graph, pit[0], n) - for pit in parent_iterators - ) - ), + (n for n in prepared_nodes if all(nx.has_path(execution_graph, pit[0], n) for pit in parent_iterators)), None, ) @@ -1130,13 +1008,13 @@ class GraphExecutionState(BaseModel): # Depth-first search with pre-order traversal is a depth-first topological sort sorted_nodes = nx.dfs_preorder_nodes(g) - + next_node = next( ( n for n in sorted_nodes - if n not in self.executed # the node must not already be executed... - and all((e[0] in self.executed for e in g.in_edges(n))) # ...and all its inputs must be executed + if n not in self.executed # the node must not already be executed... + and all((e[0] in self.executed for e in g.in_edges(n))) # ...and all its inputs must be executed ), None, ) @@ -1221,15 +1099,18 @@ class ExposedNodeOutput(BaseModel): field: str = Field(description="The field name of the output") alias: str = Field(description="The alias of the output") + class LibraryGraph(BaseModel): id: str = Field(description="The unique identifier for this library graph", default_factory=uuid.uuid4) graph: Graph = Field(description="The graph") name: str = Field(description="The name of the graph") description: str = Field(description="The description of the graph") exposed_inputs: list[ExposedNodeInput] = Field(description="The inputs exposed by this graph", default_factory=list) - exposed_outputs: list[ExposedNodeOutput] = Field(description="The outputs exposed by this graph", default_factory=list) + exposed_outputs: list[ExposedNodeOutput] = Field( + description="The outputs exposed by this graph", default_factory=list + ) - @validator('exposed_inputs', 'exposed_outputs') + @validator("exposed_inputs", "exposed_outputs") def validate_exposed_aliases(cls, v): if len(v) != len(set(i.alias for i in v)): raise ValueError("Duplicate exposed alias") @@ -1237,23 +1118,27 @@ class LibraryGraph(BaseModel): @root_validator def validate_exposed_nodes(cls, values): - graph = values['graph'] + graph = values["graph"] # Validate exposed inputs - for exposed_input in values['exposed_inputs']: + for exposed_input in values["exposed_inputs"]: if not graph.has_node(exposed_input.node_path): raise ValueError(f"Exposed input node {exposed_input.node_path} does not exist") node = graph.get_node(exposed_input.node_path) if get_input_field(node, exposed_input.field) is None: - raise ValueError(f"Exposed input field {exposed_input.field} does not exist on node {exposed_input.node_path}") + raise ValueError( + f"Exposed input field {exposed_input.field} does not exist on node {exposed_input.node_path}" + ) # Validate exposed outputs - for exposed_output in values['exposed_outputs']: + for exposed_output in values["exposed_outputs"]: if not graph.has_node(exposed_output.node_path): raise ValueError(f"Exposed output node {exposed_output.node_path} does not exist") node = graph.get_node(exposed_output.node_path) if get_output_field(node, exposed_output.field) is None: - raise ValueError(f"Exposed output field {exposed_output.field} does not exist on node {exposed_output.node_path}") + raise ValueError( + f"Exposed output field {exposed_output.field} does not exist on node {exposed_output.node_path}" + ) return values diff --git a/invokeai/app/services/image_file_storage.py b/invokeai/app/services/image_file_storage.py index 60ae613748..fb8563a3e4 100644 --- a/invokeai/app/services/image_file_storage.py +++ b/invokeai/app/services/image_file_storage.py @@ -85,9 +85,7 @@ class DiskImageFileStorage(ImageFileStorageBase): self.__cache_ids = Queue() self.__max_cache_size = 10 # TODO: get this from config - self.__output_folder: Path = ( - output_folder if isinstance(output_folder, Path) else Path(output_folder) - ) + self.__output_folder: Path = output_folder if isinstance(output_folder, Path) else Path(output_folder) self.__thumbnails_folder = self.__output_folder / "thumbnails" # Validate required output folders at launch @@ -120,7 +118,7 @@ class DiskImageFileStorage(ImageFileStorageBase): image_path = self.get_path(image_name) pnginfo = PngImagePlugin.PngInfo() - + if metadata is not None: pnginfo.add_text("invokeai_metadata", json.dumps(metadata)) if graph is not None: @@ -183,9 +181,7 @@ class DiskImageFileStorage(ImageFileStorageBase): def __set_cache(self, image_name: Path, image: PILImageType): if not image_name in self.__cache: self.__cache[image_name] = image - self.__cache_ids.put( - image_name - ) # TODO: this should refresh position for LRU cache + self.__cache_ids.put(image_name) # TODO: this should refresh position for LRU cache if len(self.__cache) > self.__max_cache_size: cache_id = self.__cache_ids.get() if cache_id in self.__cache: diff --git a/invokeai/app/services/image_record_storage.py b/invokeai/app/services/image_record_storage.py index eb69679a35..8c274ab8f9 100644 --- a/invokeai/app/services/image_record_storage.py +++ b/invokeai/app/services/image_record_storage.py @@ -426,9 +426,7 @@ class SqliteImageRecordStorage(ImageRecordStorageBase): finally: self._lock.release() - return OffsetPaginatedResults( - items=images, offset=offset, limit=limit, total=count - ) + return OffsetPaginatedResults(items=images, offset=offset, limit=limit, total=count) def delete(self, image_name: str) -> None: try: @@ -466,7 +464,6 @@ class SqliteImageRecordStorage(ImageRecordStorageBase): finally: self._lock.release() - def delete_intermediates(self) -> list[str]: try: self._lock.acquire() @@ -505,9 +502,7 @@ class SqliteImageRecordStorage(ImageRecordStorageBase): is_intermediate: bool = False, ) -> datetime: try: - metadata_json = ( - None if metadata is None else json.dumps(metadata) - ) + metadata_json = None if metadata is None else json.dumps(metadata) self._lock.acquire() self._cursor.execute( """--sql diff --git a/invokeai/app/services/images.py b/invokeai/app/services/images.py index 007f4021d4..f8376eb626 100644 --- a/invokeai/app/services/images.py +++ b/invokeai/app/services/images.py @@ -217,12 +217,8 @@ class ImageService(ImageServiceABC): session_id=session_id, ) if board_id is not None: - self._services.board_image_records.add_image_to_board( - board_id=board_id, image_name=image_name - ) - self._services.image_files.save( - image_name=image_name, image=image, metadata=metadata, graph=graph - ) + self._services.board_image_records.add_image_to_board(board_id=board_id, image_name=image_name) + self._services.image_files.save(image_name=image_name, image=image, metadata=metadata, graph=graph) image_dto = self.get_dto(image_name) return image_dto @@ -297,9 +293,7 @@ class ImageService(ImageServiceABC): if not image_record.session_id: return ImageMetadata() - session_raw = self._services.graph_execution_manager.get_raw( - image_record.session_id - ) + session_raw = self._services.graph_execution_manager.get_raw(image_record.session_id) graph = None if session_raw: @@ -364,9 +358,7 @@ class ImageService(ImageServiceABC): r, self._services.urls.get_image_url(r.image_name), self._services.urls.get_image_url(r.image_name, True), - self._services.board_image_records.get_board_for_image( - r.image_name - ), + self._services.board_image_records.get_board_for_image(r.image_name), ), results.items, ) @@ -398,11 +390,7 @@ class ImageService(ImageServiceABC): def delete_images_on_board(self, board_id: str): try: - image_names = ( - self._services.board_image_records.get_all_board_image_names_for_board( - board_id - ) - ) + image_names = self._services.board_image_records.get_all_board_image_names_for_board(board_id) for image_name in image_names: self._services.image_files.delete(image_name) self._services.image_records.delete_many(image_names) diff --git a/invokeai/app/services/invocation_queue.py b/invokeai/app/services/invocation_queue.py index eb78a542a6..963d500aa8 100644 --- a/invokeai/app/services/invocation_queue.py +++ b/invokeai/app/services/invocation_queue.py @@ -7,6 +7,7 @@ from queue import Queue from pydantic import BaseModel, Field from typing import Optional + class InvocationQueueItem(BaseModel): graph_execution_state_id: str = Field(description="The ID of the graph execution state") invocation_id: str = Field(description="The ID of the node being invoked") @@ -45,9 +46,11 @@ class MemoryInvocationQueue(InvocationQueueABC): def get(self) -> InvocationQueueItem: item = self.__queue.get() - while isinstance(item, InvocationQueueItem) \ - and item.graph_execution_state_id in self.__cancellations \ - and self.__cancellations[item.graph_execution_state_id] > item.timestamp: + while ( + isinstance(item, InvocationQueueItem) + and item.graph_execution_state_id in self.__cancellations + and self.__cancellations[item.graph_execution_state_id] > item.timestamp + ): item = self.__queue.get() # Clear old items diff --git a/invokeai/app/services/invoker.py b/invokeai/app/services/invoker.py index 951d3b17c4..1a7b0de27e 100644 --- a/invokeai/app/services/invoker.py +++ b/invokeai/app/services/invoker.py @@ -7,6 +7,7 @@ from .graph import Graph, GraphExecutionState from .invocation_queue import InvocationQueueItem from .invocation_services import InvocationServices + class Invoker: """The invoker, used to execute invocations""" @@ -16,9 +17,7 @@ class Invoker: self.services = services self._start() - def invoke( - self, graph_execution_state: GraphExecutionState, invoke_all: bool = False - ) -> Optional[str]: + def invoke(self, graph_execution_state: GraphExecutionState, invoke_all: bool = False) -> Optional[str]: """Determines the next node to invoke and enqueues it, preparing if needed. Returns the id of the queued node, or `None` if there are no nodes left to enqueue.""" diff --git a/invokeai/app/services/item_storage.py b/invokeai/app/services/item_storage.py index 709d88bf97..5fe4eb7456 100644 --- a/invokeai/app/services/item_storage.py +++ b/invokeai/app/services/item_storage.py @@ -9,13 +9,15 @@ T = TypeVar("T", bound=BaseModel) class PaginatedResults(GenericModel, Generic[T]): """Paginated results""" - #fmt: off + + # fmt: off items: list[T] = Field(description="Items") page: int = Field(description="Current Page") pages: int = Field(description="Total number of pages") per_page: int = Field(description="Number of items per page") total: int = Field(description="Total number of items in result") - #fmt: on + # fmt: on + class ItemStorageABC(ABC, Generic[T]): _on_changed_callbacks: list[Callable[[T], None]] @@ -48,9 +50,7 @@ class ItemStorageABC(ABC, Generic[T]): pass @abstractmethod - def search( - self, query: str, page: int = 0, per_page: int = 10 - ) -> PaginatedResults[T]: + def search(self, query: str, page: int = 0, per_page: int = 10) -> PaginatedResults[T]: pass def on_changed(self, on_changed: Callable[[T], None]) -> None: diff --git a/invokeai/app/services/latent_storage.py b/invokeai/app/services/latent_storage.py index 0e23d6d018..7e781c49ec 100644 --- a/invokeai/app/services/latent_storage.py +++ b/invokeai/app/services/latent_storage.py @@ -7,6 +7,7 @@ from typing import Dict, Union, Optional import torch + class LatentsStorageBase(ABC): """Responsible for storing and retrieving latents.""" @@ -25,7 +26,7 @@ class LatentsStorageBase(ABC): class ForwardCacheLatentsStorage(LatentsStorageBase): """Caches the latest N latents in memory, writing-thorugh to and reading from underlying storage""" - + __cache: Dict[str, torch.Tensor] __cache_ids: Queue __max_cache_size: int @@ -87,8 +88,6 @@ class DiskLatentsStorage(LatentsStorageBase): def delete(self, name: str) -> None: latent_path = self.get_path(name) latent_path.unlink() - def get_path(self, name: str) -> Path: return self.__output_folder / name - diff --git a/invokeai/app/services/model_manager_service.py b/invokeai/app/services/model_manager_service.py index f7d3b3a7a7..c84cc3d189 100644 --- a/invokeai/app/services/model_manager_service.py +++ b/invokeai/app/services/model_manager_service.py @@ -103,7 +103,7 @@ class ModelManagerServiceBase(ABC): } """ pass - + @abstractmethod def list_model(self, model_name: str, base_model: BaseModelType, model_type: ModelType) -> dict: """ @@ -125,7 +125,7 @@ class ModelManagerServiceBase(ABC): base_model: BaseModelType, model_type: ModelType, model_attributes: dict, - clobber: bool = False + clobber: bool = False, ) -> AddModelResult: """ Update the named model with a dictionary of attributes. Will fail with an @@ -148,12 +148,12 @@ class ModelManagerServiceBase(ABC): Update the named model with a dictionary of attributes. Will fail with a ModelNotFoundException if the name does not already exist. - On a successful update, the config will be changed in memory. Will fail - with an assertion error if provided attributes are incorrect or + On a successful update, the config will be changed in memory. Will fail + with an assertion error if provided attributes are incorrect or the model name is missing. Call commit() to write changes to disk. """ pass - + @abstractmethod def del_model( self, @@ -169,21 +169,20 @@ class ModelManagerServiceBase(ABC): pass @abstractmethod - def rename_model(self, - model_name: str, - base_model: BaseModelType, - model_type: ModelType, - new_name: str, - ): + def rename_model( + self, + model_name: str, + base_model: BaseModelType, + model_type: ModelType, + new_name: str, + ): """ Rename the indicated model. """ pass @abstractmethod - def list_checkpoint_configs( - self - )->List[Path]: + def list_checkpoint_configs(self) -> List[Path]: """ List the checkpoint config paths from ROOT/configs/stable-diffusion. """ @@ -194,7 +193,7 @@ class ModelManagerServiceBase(ABC): self, model_name: str, base_model: BaseModelType, - model_type: Union[ModelType.Main,ModelType.Vae], + model_type: Union[ModelType.Main, ModelType.Vae], ) -> AddModelResult: """ Convert a checkpoint file into a diffusers folder, deleting the cached @@ -211,11 +210,12 @@ class ModelManagerServiceBase(ABC): pass @abstractmethod - def heuristic_import(self, - items_to_import: set[str], - prediction_type_helper: Optional[Callable[[Path],SchedulerPredictionType]]=None, - )->dict[str, AddModelResult]: - '''Import a list of paths, repo_ids or URLs. Returns the set of + def heuristic_import( + self, + items_to_import: set[str], + prediction_type_helper: Optional[Callable[[Path], SchedulerPredictionType]] = None, + ) -> dict[str, AddModelResult]: + """Import a list of paths, repo_ids or URLs. Returns the set of successfully imported items. :param items_to_import: Set of strings corresponding to models to be imported. :param prediction_type_helper: A callback that receives the Path of a Stable Diffusion 2 checkpoint model and returns a SchedulerPredictionType. @@ -230,19 +230,23 @@ class ModelManagerServiceBase(ABC): The result is a set of successfully installed models. Each element of the set is a dict corresponding to the newly-created OmegaConf stanza for that model. - ''' + """ pass @abstractmethod def merge_models( - self, - model_names: List[str] = Field(default=None, min_items=2, max_items=3, description="List of model names to merge"), - base_model: Union[BaseModelType,str] = Field(default=None, description="Base model shared by all models to be merged"), - merged_model_name: str = Field(default=None, description="Name of destination model after merging"), - alpha: Optional[float] = 0.5, - interp: Optional[MergeInterpolationMethod] = None, - force: Optional[bool] = False, - merge_dest_directory: Optional[Path] = None + self, + model_names: List[str] = Field( + default=None, min_items=2, max_items=3, description="List of model names to merge" + ), + base_model: Union[BaseModelType, str] = Field( + default=None, description="Base model shared by all models to be merged" + ), + merged_model_name: str = Field(default=None, description="Name of destination model after merging"), + alpha: Optional[float] = 0.5, + interp: Optional[MergeInterpolationMethod] = None, + force: Optional[bool] = False, + merge_dest_directory: Optional[Path] = None, ) -> AddModelResult: """ Merge two to three diffusrs pipeline models and save as a new model. @@ -250,27 +254,27 @@ class ModelManagerServiceBase(ABC): :param base_model: Base model to use for all models :param merged_model_name: Name of destination merged model :param alpha: Alpha strength to apply to 2d and 3d model - :param interp: Interpolation method. None (default) + :param interp: Interpolation method. None (default) :param merge_dest_directory: Save the merged model to the designated directory (with 'merged_model_name' appended) """ pass @abstractmethod - def search_for_models(self, directory: Path)->List[Path]: + def search_for_models(self, directory: Path) -> List[Path]: """ Return list of all models found in the designated directory. """ pass - + @abstractmethod def sync_to_config(self): """ - Re-read models.yaml, rescan the models directory, and reimport models + Re-read models.yaml, rescan the models directory, and reimport models in the autoimport directories. Call after making changes outside the model manager API. """ pass - + @abstractmethod def commit(self, conf_file: Optional[Path] = None) -> None: """ @@ -280,9 +284,11 @@ class ModelManagerServiceBase(ABC): """ pass + # simple implementation class ModelManagerService(ModelManagerServiceBase): """Responsible for managing models on disk and in memory""" + def __init__( self, config: InvokeAIAppConfig, @@ -298,17 +304,17 @@ class ModelManagerService(ModelManagerServiceBase): config_file = config.model_conf_path else: config_file = config.root_dir / "configs/models.yaml" - - logger.debug(f'Config file={config_file}') + + logger.debug(f"Config file={config_file}") device = torch.device(choose_torch_device()) - device_name = torch.cuda.get_device_name() if device==torch.device('cuda') else '' - logger.info(f'GPU device = {device} {device_name}') + device_name = torch.cuda.get_device_name() if device == torch.device("cuda") else "" + logger.info(f"GPU device = {device} {device_name}") precision = config.precision if precision == "auto": precision = choose_precision(device) - dtype = torch.float32 if precision == 'float32' else torch.float16 + dtype = torch.float32 if precision == "float32" else torch.float16 # this is transitional backward compatibility # support for the deprecated `max_loaded_models` @@ -316,9 +322,7 @@ class ModelManagerService(ModelManagerServiceBase): # cache size is set to 2.5 GB times # the number of max_loaded_models. Otherwise # use new `max_cache_size` config setting - max_cache_size = config.max_cache_size \ - if hasattr(config,'max_cache_size') \ - else config.max_loaded_models * 2.5 + max_cache_size = config.max_cache_size if hasattr(config, "max_cache_size") else config.max_loaded_models * 2.5 logger.debug(f"Maximum RAM cache size: {max_cache_size} GiB") @@ -332,7 +336,7 @@ class ModelManagerService(ModelManagerServiceBase): sequential_offload=sequential_offload, logger=logger, ) - logger.info('Model manager service initialized') + logger.info("Model manager service initialized") def get_model( self, @@ -371,7 +375,7 @@ class ModelManagerService(ModelManagerServiceBase): base_model=base_model, model_type=model_type, submodel=submodel, - model_info=model_info + model_info=model_info, ) return model_info @@ -405,9 +409,7 @@ class ModelManagerService(ModelManagerServiceBase): return self.mgr.model_names() def list_models( - self, - base_model: Optional[BaseModelType] = None, - model_type: Optional[ModelType] = None + self, base_model: Optional[BaseModelType] = None, model_type: Optional[ModelType] = None ) -> list[dict]: """ Return a list of models. @@ -418,9 +420,7 @@ class ModelManagerService(ModelManagerServiceBase): """ Return information about the model using the same format as list_models() """ - return self.mgr.list_model(model_name=model_name, - base_model=base_model, - model_type=model_type) + return self.mgr.list_model(model_name=model_name, base_model=base_model, model_type=model_type) def add_model( self, @@ -429,7 +429,7 @@ class ModelManagerService(ModelManagerServiceBase): model_type: ModelType, model_attributes: dict, clobber: bool = False, - )->None: + ) -> None: """ Update the named model with a dictionary of attributes. Will fail with an assertion error if the name already exists. Pass clobber=True to overwrite. @@ -437,7 +437,7 @@ class ModelManagerService(ModelManagerServiceBase): with an assertion error if provided attributes are incorrect or the model name is missing. Call commit() to write changes to disk. """ - self.logger.debug(f'add/update model {model_name}') + self.logger.debug(f"add/update model {model_name}") return self.mgr.add_model(model_name, base_model, model_type, model_attributes, clobber) def update_model( @@ -450,15 +450,15 @@ class ModelManagerService(ModelManagerServiceBase): """ Update the named model with a dictionary of attributes. Will fail with a ModelNotFoundException exception if the name does not already exist. - On a successful update, the config will be changed in memory. Will fail - with an assertion error if provided attributes are incorrect or + On a successful update, the config will be changed in memory. Will fail + with an assertion error if provided attributes are incorrect or the model name is missing. Call commit() to write changes to disk. """ - self.logger.debug(f'update model {model_name}') + self.logger.debug(f"update model {model_name}") if not self.model_exists(model_name, base_model, model_type): raise ModelNotFoundException(f"Unknown model {model_name}") return self.add_model(model_name, base_model, model_type, model_attributes, clobber=True) - + def del_model( self, model_name: str, @@ -470,7 +470,7 @@ class ModelManagerService(ModelManagerServiceBase): then the underlying weight file or diffusers directory will be deleted as well. """ - self.logger.debug(f'delete model {model_name}') + self.logger.debug(f"delete model {model_name}") self.mgr.del_model(model_name, base_model, model_type) self.mgr.commit() @@ -478,8 +478,10 @@ class ModelManagerService(ModelManagerServiceBase): self, model_name: str, base_model: BaseModelType, - model_type: Union[ModelType.Main,ModelType.Vae], - convert_dest_directory: Optional[Path] = Field(default=None, description="Optional directory location for merged model"), + model_type: Union[ModelType.Main, ModelType.Vae], + convert_dest_directory: Optional[Path] = Field( + default=None, description="Optional directory location for merged model" + ), ) -> AddModelResult: """ Convert a checkpoint file into a diffusers folder, deleting the cached @@ -494,10 +496,10 @@ class ModelManagerService(ModelManagerServiceBase): also raise a ValueError in the event that there is a similarly-named diffusers directory already in place. """ - self.logger.debug(f'convert model {model_name}') + self.logger.debug(f"convert model {model_name}") return self.mgr.convert_model(model_name, base_model, model_type, convert_dest_directory) - def commit(self, conf_file: Optional[Path]=None): + def commit(self, conf_file: Optional[Path] = None): """ Write current configuration out to the indicated file. If no conf_file is provided, then replaces the @@ -524,7 +526,7 @@ class ModelManagerService(ModelManagerServiceBase): base_model=base_model, model_type=model_type, submodel=submodel, - model_info=model_info + model_info=model_info, ) else: context.services.events.emit_model_load_started( @@ -535,16 +537,16 @@ class ModelManagerService(ModelManagerServiceBase): submodel=submodel, ) - @property def logger(self): return self.mgr.logger - def heuristic_import(self, - items_to_import: set[str], - prediction_type_helper: Optional[Callable[[Path],SchedulerPredictionType]]=None, - )->dict[str, AddModelResult]: - '''Import a list of paths, repo_ids or URLs. Returns the set of + def heuristic_import( + self, + items_to_import: set[str], + prediction_type_helper: Optional[Callable[[Path], SchedulerPredictionType]] = None, + ) -> dict[str, AddModelResult]: + """Import a list of paths, repo_ids or URLs. Returns the set of successfully imported items. :param items_to_import: Set of strings corresponding to models to be imported. :param prediction_type_helper: A callback that receives the Path of a Stable Diffusion 2 checkpoint model and returns a SchedulerPredictionType. @@ -559,18 +561,24 @@ class ModelManagerService(ModelManagerServiceBase): The result is a set of successfully installed models. Each element of the set is a dict corresponding to the newly-created OmegaConf stanza for that model. - ''' - return self.mgr.heuristic_import(items_to_import, prediction_type_helper) + """ + return self.mgr.heuristic_import(items_to_import, prediction_type_helper) def merge_models( - self, - model_names: List[str] = Field(default=None, min_items=2, max_items=3, description="List of model names to merge"), - base_model: Union[BaseModelType,str] = Field(default=None, description="Base model shared by all models to be merged"), - merged_model_name: str = Field(default=None, description="Name of destination model after merging"), - alpha: Optional[float] = 0.5, - interp: Optional[MergeInterpolationMethod] = None, - force: Optional[bool] = False, - merge_dest_directory: Optional[Path] = Field(default=None, description="Optional directory location for merged model"), + self, + model_names: List[str] = Field( + default=None, min_items=2, max_items=3, description="List of model names to merge" + ), + base_model: Union[BaseModelType, str] = Field( + default=None, description="Base model shared by all models to be merged" + ), + merged_model_name: str = Field(default=None, description="Name of destination model after merging"), + alpha: Optional[float] = 0.5, + interp: Optional[MergeInterpolationMethod] = None, + force: Optional[bool] = False, + merge_dest_directory: Optional[Path] = Field( + default=None, description="Optional directory location for merged model" + ), ) -> AddModelResult: """ Merge two to three diffusrs pipeline models and save as a new model. @@ -578,25 +586,25 @@ class ModelManagerService(ModelManagerServiceBase): :param base_model: Base model to use for all models :param merged_model_name: Name of destination merged model :param alpha: Alpha strength to apply to 2d and 3d model - :param interp: Interpolation method. None (default) + :param interp: Interpolation method. None (default) :param merge_dest_directory: Save the merged model to the designated directory (with 'merged_model_name' appended) """ merger = ModelMerger(self.mgr) try: result = merger.merge_diffusion_models_and_save( - model_names = model_names, - base_model = base_model, - merged_model_name = merged_model_name, - alpha = alpha, - interp = interp, - force = force, + model_names=model_names, + base_model=base_model, + merged_model_name=merged_model_name, + alpha=alpha, + interp=interp, + force=force, merge_dest_directory=merge_dest_directory, ) except AssertionError as e: raise ValueError(e) return result - def search_for_models(self, directory: Path)->List[Path]: + def search_for_models(self, directory: Path) -> List[Path]: """ Return list of all models found in the designated directory. """ @@ -605,28 +613,29 @@ class ModelManagerService(ModelManagerServiceBase): def sync_to_config(self): """ - Re-read models.yaml, rescan the models directory, and reimport models + Re-read models.yaml, rescan the models directory, and reimport models in the autoimport directories. Call after making changes outside the model manager API. """ return self.mgr.sync_to_config() - def list_checkpoint_configs(self)->List[Path]: + def list_checkpoint_configs(self) -> List[Path]: """ List the checkpoint config paths from ROOT/configs/stable-diffusion. """ config = self.mgr.app_config conf_path = config.legacy_conf_path root_path = config.root_path - return [(conf_path / x).relative_to(root_path) for x in conf_path.glob('**/*.yaml')] + return [(conf_path / x).relative_to(root_path) for x in conf_path.glob("**/*.yaml")] - def rename_model(self, - model_name: str, - base_model: BaseModelType, - model_type: ModelType, - new_name: str = None, - new_base: BaseModelType = None, - ): + def rename_model( + self, + model_name: str, + base_model: BaseModelType, + model_type: ModelType, + new_name: str = None, + new_base: BaseModelType = None, + ): """ Rename the indicated model. Can provide a new name and/or a new base. :param model_name: Current name of the model @@ -635,10 +644,10 @@ class ModelManagerService(ModelManagerServiceBase): :param new_name: New name for the model :param new_base: New base for the model """ - self.mgr.rename_model(base_model = base_model, - model_type = model_type, - model_name = model_name, - new_name = new_name, - new_base = new_base, - ) - + self.mgr.rename_model( + base_model=base_model, + model_type=model_type, + model_name=model_name, + new_name=new_name, + new_base=new_base, + ) diff --git a/invokeai/app/services/models/board_record.py b/invokeai/app/services/models/board_record.py index bf5401b209..658698e794 100644 --- a/invokeai/app/services/models/board_record.py +++ b/invokeai/app/services/models/board_record.py @@ -11,30 +11,20 @@ class BoardRecord(BaseModel): """The unique ID of the board.""" board_name: str = Field(description="The name of the board.") """The name of the board.""" - created_at: Union[datetime, str] = Field( - description="The created timestamp of the board." - ) + created_at: Union[datetime, str] = Field(description="The created timestamp of the board.") """The created timestamp of the image.""" - updated_at: Union[datetime, str] = Field( - description="The updated timestamp of the board." - ) + updated_at: Union[datetime, str] = Field(description="The updated timestamp of the board.") """The updated timestamp of the image.""" - deleted_at: Union[datetime, str, None] = Field( - description="The deleted timestamp of the board." - ) + deleted_at: Union[datetime, str, None] = Field(description="The deleted timestamp of the board.") """The updated timestamp of the image.""" - cover_image_name: Optional[str] = Field( - description="The name of the cover image of the board." - ) + cover_image_name: Optional[str] = Field(description="The name of the cover image of the board.") """The name of the cover image of the board.""" class BoardDTO(BoardRecord): """Deserialized board record with cover image URL and image count.""" - cover_image_name: Optional[str] = Field( - description="The name of the board's cover image." - ) + cover_image_name: Optional[str] = Field(description="The name of the board's cover image.") """The URL of the thumbnail of the most recent image in the board.""" image_count: int = Field(description="The number of images in the board.") """The number of images in the board.""" diff --git a/invokeai/app/services/models/image_record.py b/invokeai/app/services/models/image_record.py index cf10f6e8b2..a105d03ba8 100644 --- a/invokeai/app/services/models/image_record.py +++ b/invokeai/app/services/models/image_record.py @@ -20,17 +20,11 @@ class ImageRecord(BaseModel): """The actual width of the image in px. This may be different from the width in metadata.""" height: int = Field(description="The height of the image in px.") """The actual height of the image in px. This may be different from the height in metadata.""" - created_at: Union[datetime.datetime, str] = Field( - description="The created timestamp of the image." - ) + created_at: Union[datetime.datetime, str] = Field(description="The created timestamp of the image.") """The created timestamp of the image.""" - updated_at: Union[datetime.datetime, str] = Field( - description="The updated timestamp of the image." - ) + updated_at: Union[datetime.datetime, str] = Field(description="The updated timestamp of the image.") """The updated timestamp of the image.""" - deleted_at: Union[datetime.datetime, str, None] = Field( - description="The deleted timestamp of the image." - ) + deleted_at: Union[datetime.datetime, str, None] = Field(description="The deleted timestamp of the image.") """The deleted timestamp of the image.""" is_intermediate: bool = Field(description="Whether this is an intermediate image.") """Whether this is an intermediate image.""" @@ -55,18 +49,14 @@ class ImageRecordChanges(BaseModel, extra=Extra.forbid): - `is_intermediate`: change the image's `is_intermediate` flag """ - image_category: Optional[ImageCategory] = Field( - description="The image's new category." - ) + image_category: Optional[ImageCategory] = Field(description="The image's new category.") """The image's new category.""" session_id: Optional[StrictStr] = Field( default=None, description="The image's new session ID.", ) """The image's new session ID.""" - is_intermediate: Optional[StrictBool] = Field( - default=None, description="The image's new `is_intermediate` flag." - ) + is_intermediate: Optional[StrictBool] = Field(default=None, description="The image's new `is_intermediate` flag.") """The image's new `is_intermediate` flag.""" @@ -84,9 +74,7 @@ class ImageUrlsDTO(BaseModel): class ImageDTO(ImageRecord, ImageUrlsDTO): """Deserialized image record, enriched for the frontend.""" - board_id: Optional[str] = Field( - description="The id of the board the image belongs to, if one exists." - ) + board_id: Optional[str] = Field(description="The id of the board the image belongs to, if one exists.") """The id of the board the image belongs to, if one exists.""" pass @@ -110,12 +98,8 @@ def deserialize_image_record(image_dict: dict) -> ImageRecord: # TODO: do we really need to handle default values here? ideally the data is the correct shape... image_name = image_dict.get("image_name", "unknown") - image_origin = ResourceOrigin( - image_dict.get("image_origin", ResourceOrigin.INTERNAL.value) - ) - image_category = ImageCategory( - image_dict.get("image_category", ImageCategory.GENERAL.value) - ) + image_origin = ResourceOrigin(image_dict.get("image_origin", ResourceOrigin.INTERNAL.value)) + image_category = ImageCategory(image_dict.get("image_category", ImageCategory.GENERAL.value)) width = image_dict.get("width", 0) height = image_dict.get("height", 0) session_id = image_dict.get("session_id", None) diff --git a/invokeai/app/services/processor.py b/invokeai/app/services/processor.py index 5995e4ffc3..50fe217e05 100644 --- a/invokeai/app/services/processor.py +++ b/invokeai/app/services/processor.py @@ -8,6 +8,8 @@ from .invoker import InvocationProcessorABC, Invoker from ..models.exceptions import CanceledException import invokeai.backend.util.logging as logger + + class DefaultInvocationProcessor(InvocationProcessorABC): __invoker_thread: Thread __stop_event: Event @@ -24,9 +26,7 @@ class DefaultInvocationProcessor(InvocationProcessorABC): target=self.__process, kwargs=dict(stop_event=self.__stop_event), ) - self.__invoker_thread.daemon = ( - True # TODO: make async and do not use threads - ) + self.__invoker_thread.daemon = True # TODO: make async and do not use threads self.__invoker_thread.start() def stop(self, *args, **kwargs) -> None: @@ -47,10 +47,8 @@ class DefaultInvocationProcessor(InvocationProcessorABC): continue try: - graph_execution_state = ( - self.__invoker.services.graph_execution_manager.get( - queue_item.graph_execution_state_id - ) + graph_execution_state = self.__invoker.services.graph_execution_manager.get( + queue_item.graph_execution_state_id ) except Exception as e: self.__invoker.services.logger.error("Exception while retrieving session:\n%s" % e) @@ -60,11 +58,9 @@ class DefaultInvocationProcessor(InvocationProcessorABC): error=traceback.format_exc(), ) continue - + try: - invocation = graph_execution_state.execution_graph.get_node( - queue_item.invocation_id - ) + invocation = graph_execution_state.execution_graph.get_node(queue_item.invocation_id) except Exception as e: self.__invoker.services.logger.error("Exception while retrieving invocation:\n%s" % e) self.__invoker.services.events.emit_invocation_retrieval_error( @@ -82,7 +78,7 @@ class DefaultInvocationProcessor(InvocationProcessorABC): self.__invoker.services.events.emit_invocation_started( graph_execution_state_id=graph_execution_state.id, node=invocation.dict(), - source_node_id=source_node_id + source_node_id=source_node_id, ) # Invoke @@ -95,18 +91,14 @@ class DefaultInvocationProcessor(InvocationProcessorABC): ) # Check queue to see if this is canceled, and skip if so - if self.__invoker.services.queue.is_canceled( - graph_execution_state.id - ): + if self.__invoker.services.queue.is_canceled(graph_execution_state.id): continue # Save outputs and history graph_execution_state.complete(invocation.id, outputs) # Save the state changes - self.__invoker.services.graph_execution_manager.set( - graph_execution_state - ) + self.__invoker.services.graph_execution_manager.set(graph_execution_state) # Send complete event self.__invoker.services.events.emit_invocation_complete( @@ -130,9 +122,7 @@ class DefaultInvocationProcessor(InvocationProcessorABC): graph_execution_state.set_node_error(invocation.id, error) # Save the state changes - self.__invoker.services.graph_execution_manager.set( - graph_execution_state - ) + self.__invoker.services.graph_execution_manager.set(graph_execution_state) self.__invoker.services.logger.error("Error while invoking:\n%s" % e) # Send error event @@ -147,9 +137,7 @@ class DefaultInvocationProcessor(InvocationProcessorABC): pass # Check queue to see if this is canceled, and skip if so - if self.__invoker.services.queue.is_canceled( - graph_execution_state.id - ): + if self.__invoker.services.queue.is_canceled(graph_execution_state.id): continue # Queue any further commands if invoking all @@ -164,12 +152,10 @@ class DefaultInvocationProcessor(InvocationProcessorABC): node=invocation.dict(), source_node_id=source_node_id, error_type=e.__class__.__name__, - error=traceback.format_exc() + error=traceback.format_exc(), ) elif is_complete: - self.__invoker.services.events.emit_graph_execution_complete( - graph_execution_state.id - ) + self.__invoker.services.events.emit_graph_execution_complete(graph_execution_state.id) except KeyboardInterrupt: pass # Log something? KeyboardInterrupt is probably not going to be seen by the processor diff --git a/invokeai/app/services/sqlite.py b/invokeai/app/services/sqlite.py index 8902415096..855f3f1939 100644 --- a/invokeai/app/services/sqlite.py +++ b/invokeai/app/services/sqlite.py @@ -66,9 +66,7 @@ class SqliteItemStorage(ItemStorageABC, Generic[T]): def get(self, id: str) -> Optional[T]: try: self._lock.acquire() - self._cursor.execute( - f"""SELECT item FROM {self._table_name} WHERE id = ?;""", (str(id),) - ) + self._cursor.execute(f"""SELECT item FROM {self._table_name} WHERE id = ?;""", (str(id),)) result = self._cursor.fetchone() finally: self._lock.release() @@ -81,9 +79,7 @@ class SqliteItemStorage(ItemStorageABC, Generic[T]): def get_raw(self, id: str) -> Optional[str]: try: self._lock.acquire() - self._cursor.execute( - f"""SELECT item FROM {self._table_name} WHERE id = ?;""", (str(id),) - ) + self._cursor.execute(f"""SELECT item FROM {self._table_name} WHERE id = ?;""", (str(id),)) result = self._cursor.fetchone() finally: self._lock.release() @@ -96,9 +92,7 @@ class SqliteItemStorage(ItemStorageABC, Generic[T]): def delete(self, id: str): try: self._lock.acquire() - self._cursor.execute( - f"""DELETE FROM {self._table_name} WHERE id = ?;""", (str(id),) - ) + self._cursor.execute(f"""DELETE FROM {self._table_name} WHERE id = ?;""", (str(id),)) self._conn.commit() finally: self._lock.release() @@ -122,13 +116,9 @@ class SqliteItemStorage(ItemStorageABC, Generic[T]): pageCount = int(count / per_page) + 1 - return PaginatedResults[T]( - items=items, page=page, pages=pageCount, per_page=per_page, total=count - ) + return PaginatedResults[T](items=items, page=page, pages=pageCount, per_page=per_page, total=count) - def search( - self, query: str, page: int = 0, per_page: int = 10 - ) -> PaginatedResults[T]: + def search(self, query: str, page: int = 0, per_page: int = 10) -> PaginatedResults[T]: try: self._lock.acquire() self._cursor.execute( @@ -149,6 +139,4 @@ class SqliteItemStorage(ItemStorageABC, Generic[T]): pageCount = int(count / per_page) + 1 - return PaginatedResults[T]( - items=items, page=page, pages=pageCount, per_page=per_page, total=count - ) + return PaginatedResults[T](items=items, page=page, pages=pageCount, per_page=per_page, total=count) diff --git a/invokeai/app/util/controlnet_utils.py b/invokeai/app/util/controlnet_utils.py index 342fa147c5..6f2c49fec2 100644 --- a/invokeai/app/util/controlnet_utils.py +++ b/invokeai/app/util/controlnet_utils.py @@ -17,16 +17,8 @@ from controlnet_aux.util import HWC3, resize_image # If you use this, please Cite "High Quality Edge Thinning using Pure Python", Lvmin Zhang, In Mikubill/sd-webui-controlnet. lvmin_kernels_raw = [ - np.array([ - [-1, -1, -1], - [0, 1, 0], - [1, 1, 1] - ], dtype=np.int32), - np.array([ - [0, -1, -1], - [1, 1, -1], - [0, 1, 0] - ], dtype=np.int32) + np.array([[-1, -1, -1], [0, 1, 0], [1, 1, 1]], dtype=np.int32), + np.array([[0, -1, -1], [1, 1, -1], [0, 1, 0]], dtype=np.int32), ] lvmin_kernels = [] @@ -36,16 +28,8 @@ lvmin_kernels += [np.rot90(x, k=2, axes=(0, 1)) for x in lvmin_kernels_raw] lvmin_kernels += [np.rot90(x, k=3, axes=(0, 1)) for x in lvmin_kernels_raw] lvmin_prunings_raw = [ - np.array([ - [-1, -1, -1], - [-1, 1, -1], - [0, 0, -1] - ], dtype=np.int32), - np.array([ - [-1, -1, -1], - [-1, 1, -1], - [-1, 0, 0] - ], dtype=np.int32) + np.array([[-1, -1, -1], [-1, 1, -1], [0, 0, -1]], dtype=np.int32), + np.array([[-1, -1, -1], [-1, 1, -1], [-1, 0, 0]], dtype=np.int32), ] lvmin_prunings = [] @@ -99,10 +83,10 @@ def nake_nms(x): ################################################################################ # FIXME: not using yet, if used in the future will most likely require modification of preprocessors def pixel_perfect_resolution( - image: np.ndarray, - target_H: int, - target_W: int, - resize_mode: str, + image: np.ndarray, + target_H: int, + target_W: int, + resize_mode: str, ) -> int: """ Calculate the estimated resolution for resizing an image while preserving aspect ratio. @@ -135,7 +119,7 @@ def pixel_perfect_resolution( if resize_mode == "fill_resize": estimation = min(k0, k1) * float(min(raw_H, raw_W)) - else: # "crop_resize" or "just_resize" (or possibly "just_resize_simple"?) + else: # "crop_resize" or "just_resize" (or possibly "just_resize_simple"?) estimation = max(k0, k1) * float(min(raw_H, raw_W)) # print(f"Pixel Perfect Computation:") @@ -154,13 +138,7 @@ def pixel_perfect_resolution( # modified for InvokeAI ########################################################################### # def detectmap_proc(detected_map, module, resize_mode, h, w): -def np_img_resize( - np_img: np.ndarray, - resize_mode: str, - h: int, - w: int, - device: torch.device = torch.device('cpu') -): +def np_img_resize(np_img: np.ndarray, resize_mode: str, h: int, w: int, device: torch.device = torch.device("cpu")): # if 'inpaint' in module: # np_img = np_img.astype(np.float32) # else: @@ -184,15 +162,14 @@ def np_img_resize( # below is very boring but do not change these. If you change these Apple or Mac may fail. y = torch.from_numpy(y) y = y.float() / 255.0 - y = rearrange(y, 'h w c -> 1 c h w') + y = rearrange(y, "h w c -> 1 c h w") y = y.clone() # y = y.to(devices.get_device_for("controlnet")) y = y.to(device) y = y.clone() return y - def high_quality_resize(x: np.ndarray, - size): + def high_quality_resize(x: np.ndarray, size): # Written by lvmin # Super high-quality control map up-scaling, considering binary, seg, and one-pixel edges inpaint_mask = None @@ -244,7 +221,7 @@ def np_img_resize( return y # if resize_mode == external_code.ResizeMode.RESIZE: - if resize_mode == "just_resize": # RESIZE + if resize_mode == "just_resize": # RESIZE np_img = high_quality_resize(np_img, (w, h)) np_img = safe_numpy(np_img) return get_pytorch_control(np_img), np_img @@ -270,20 +247,21 @@ def np_img_resize( new_h, new_w, _ = np_img.shape pad_h = max(0, (h - new_h) // 2) pad_w = max(0, (w - new_w) // 2) - high_quality_background[pad_h:pad_h + new_h, pad_w:pad_w + new_w] = np_img + high_quality_background[pad_h : pad_h + new_h, pad_w : pad_w + new_w] = np_img np_img = high_quality_background np_img = safe_numpy(np_img) return get_pytorch_control(np_img), np_img - else: # resize_mode == "crop_resize" (INNER_FIT) + else: # resize_mode == "crop_resize" (INNER_FIT) k = max(k0, k1) np_img = high_quality_resize(np_img, (safeint(old_w * k), safeint(old_h * k))) new_h, new_w, _ = np_img.shape pad_h = max(0, (new_h - h) // 2) pad_w = max(0, (new_w - w) // 2) - np_img = np_img[pad_h:pad_h + h, pad_w:pad_w + w] + np_img = np_img[pad_h : pad_h + h, pad_w : pad_w + w] np_img = safe_numpy(np_img) return get_pytorch_control(np_img), np_img + def prepare_control_image( # image used to be Union[PIL.Image.Image, List[PIL.Image.Image], torch.Tensor, List[torch.Tensor]] # but now should be able to assume that image is a single PIL.Image, which simplifies things @@ -301,15 +279,17 @@ def prepare_control_image( resize_mode="just_resize_simple", ): # FIXME: implement "crop_resize_simple" and "fill_resize_simple", or pull them out - if (resize_mode == "just_resize_simple" or - resize_mode == "crop_resize_simple" or - resize_mode == "fill_resize_simple"): + if ( + resize_mode == "just_resize_simple" + or resize_mode == "crop_resize_simple" + or resize_mode == "fill_resize_simple" + ): image = image.convert("RGB") - if (resize_mode == "just_resize_simple"): + if resize_mode == "just_resize_simple": image = image.resize((width, height), resample=PIL_INTERPOLATION["lanczos"]) - elif (resize_mode == "crop_resize_simple"): # not yet implemented + elif resize_mode == "crop_resize_simple": # not yet implemented pass - elif (resize_mode == "fill_resize_simple"): # not yet implemented + elif resize_mode == "fill_resize_simple": # not yet implemented pass nimage = np.array(image) nimage = nimage[None, :] @@ -320,7 +300,7 @@ def prepare_control_image( timage = torch.from_numpy(nimage) # use fancy lvmin controlnet resizing - elif (resize_mode == "just_resize" or resize_mode == "crop_resize" or resize_mode == "fill_resize"): + elif resize_mode == "just_resize" or resize_mode == "crop_resize" or resize_mode == "fill_resize": nimage = np.array(image) timage, nimage = np_img_resize( np_img=nimage, @@ -336,7 +316,7 @@ def prepare_control_image( exit(1) timage = timage.to(device=device, dtype=dtype) - cfg_injection = (control_mode == "more_control" or control_mode == "unbalanced") + cfg_injection = control_mode == "more_control" or control_mode == "unbalanced" if do_classifier_free_guidance and not cfg_injection: timage = torch.cat([timage] * 2) return timage diff --git a/invokeai/app/util/step_callback.py b/invokeai/app/util/step_callback.py index 1e8939b0bf..994d83e705 100644 --- a/invokeai/app/util/step_callback.py +++ b/invokeai/app/util/step_callback.py @@ -9,19 +9,16 @@ from ...backend.stable_diffusion import PipelineIntermediateState from invokeai.app.services.config import InvokeAIAppConfig -def sample_to_lowres_estimated_image(samples, latent_rgb_factors, smooth_matrix = None): +def sample_to_lowres_estimated_image(samples, latent_rgb_factors, smooth_matrix=None): latent_image = samples[0].permute(1, 2, 0) @ latent_rgb_factors if smooth_matrix is not None: latent_image = latent_image.unsqueeze(0).permute(3, 0, 1, 2) - latent_image = torch.nn.functional.conv2d(latent_image, smooth_matrix.reshape((1,1,3,3)), padding=1) + latent_image = torch.nn.functional.conv2d(latent_image, smooth_matrix.reshape((1, 1, 3, 3)), padding=1) latent_image = latent_image.permute(1, 2, 3, 0).squeeze(0) latents_ubyte = ( - ((latent_image + 1) / 2) - .clamp(0, 1) # change scale from -1..1 to 0..1 - .mul(0xFF) # to 0..255 - .byte() + ((latent_image + 1) / 2).clamp(0, 1).mul(0xFF).byte() # change scale from -1..1 to 0..1 # to 0..255 ).cpu() return Image.fromarray(latents_ubyte.numpy()) @@ -92,6 +89,7 @@ def stable_diffusion_step_callback( total_steps=node["steps"], ) + def stable_diffusion_xl_step_callback( context: InvocationContext, node: dict, @@ -106,9 +104,9 @@ def stable_diffusion_xl_step_callback( sdxl_latent_rgb_factors = torch.tensor( [ # R G B - [ 0.3816, 0.4930, 0.5320], - [-0.3753, 0.1631, 0.1739], - [ 0.1770, 0.3588, -0.2048], + [0.3816, 0.4930, 0.5320], + [-0.3753, 0.1631, 0.1739], + [0.1770, 0.3588, -0.2048], [-0.4350, -0.2644, -0.4289], ], dtype=sample.dtype, @@ -117,9 +115,9 @@ def stable_diffusion_xl_step_callback( sdxl_smooth_matrix = torch.tensor( [ - #[ 0.0478, 0.1285, 0.0478], - #[ 0.1285, 0.2948, 0.1285], - #[ 0.0478, 0.1285, 0.0478], + # [ 0.0478, 0.1285, 0.0478], + # [ 0.1285, 0.2948, 0.1285], + # [ 0.0478, 0.1285, 0.0478], [0.0358, 0.0964, 0.0358], [0.0964, 0.4711, 0.0964], [0.0358, 0.0964, 0.0358], @@ -143,4 +141,4 @@ def stable_diffusion_xl_step_callback( progress_image=ProgressImage(width=width, height=height, dataURL=dataURL), step=step, total_steps=total_steps, - ) \ No newline at end of file + ) diff --git a/invokeai/backend/__init__.py b/invokeai/backend/__init__.py index a33b70ceb4..aa2a1f1ca6 100644 --- a/invokeai/backend/__init__.py +++ b/invokeai/backend/__init__.py @@ -1,15 +1,6 @@ """ Initialization file for invokeai.backend """ -from .generator import ( - InvokeAIGeneratorBasicParams, - InvokeAIGenerator, - InvokeAIGeneratorOutput, - Img2Img, - Inpaint -) -from .model_management import ( - ModelManager, ModelCache, BaseModelType, - ModelType, SubModelType, ModelInfo - ) +from .generator import InvokeAIGeneratorBasicParams, InvokeAIGenerator, InvokeAIGeneratorOutput, Img2Img, Inpaint +from .model_management import ModelManager, ModelCache, BaseModelType, ModelType, SubModelType, ModelInfo from .model_management.models import SilenceWarnings diff --git a/invokeai/backend/generator/base.py b/invokeai/backend/generator/base.py index 8af8d399d5..af3231a7d1 100644 --- a/invokeai/backend/generator/base.py +++ b/invokeai/backend/generator/base.py @@ -33,61 +33,66 @@ from ..stable_diffusion.schedulers import SCHEDULER_MAP downsampling = 8 + @dataclass class InvokeAIGeneratorBasicParams: - seed: Optional[int]=None - width: int=512 - height: int=512 - cfg_scale: float=7.5 - steps: int=20 - ddim_eta: float=0.0 - scheduler: str='ddim' - precision: str='float16' - perlin: float=0.0 - threshold: float=0.0 - seamless: bool=False - seamless_axes: List[str]=field(default_factory=lambda: ['x', 'y']) - h_symmetry_time_pct: Optional[float]=None - v_symmetry_time_pct: Optional[float]=None + seed: Optional[int] = None + width: int = 512 + height: int = 512 + cfg_scale: float = 7.5 + steps: int = 20 + ddim_eta: float = 0.0 + scheduler: str = "ddim" + precision: str = "float16" + perlin: float = 0.0 + threshold: float = 0.0 + seamless: bool = False + seamless_axes: List[str] = field(default_factory=lambda: ["x", "y"]) + h_symmetry_time_pct: Optional[float] = None + v_symmetry_time_pct: Optional[float] = None variation_amount: float = 0.0 - with_variations: list=field(default_factory=list) + with_variations: list = field(default_factory=list) + @dataclass class InvokeAIGeneratorOutput: - ''' + """ InvokeAIGeneratorOutput is a dataclass that contains the outputs of a generation operation, including the image, its seed, the model name used to generate the image and the model hash, as well as all the generate() parameters that went into generating the image (in .params, also available as attributes) - ''' + """ + image: Image.Image seed: int model_hash: str attention_maps_images: List[Image.Image] params: Namespace + # we are interposing a wrapper around the original Generator classes so that # old code that calls Generate will continue to work. class InvokeAIGenerator(metaclass=ABCMeta): - def __init__(self, - model_info: dict, - params: InvokeAIGeneratorBasicParams=InvokeAIGeneratorBasicParams(), - **kwargs, - ): - self.model_info=model_info - self.params=params + def __init__( + self, + model_info: dict, + params: InvokeAIGeneratorBasicParams = InvokeAIGeneratorBasicParams(), + **kwargs, + ): + self.model_info = model_info + self.params = params self.kwargs = kwargs def generate( self, conditioning: tuple, scheduler, - callback: Optional[Callable]=None, - step_callback: Optional[Callable]=None, - iterations: int=1, + callback: Optional[Callable] = None, + step_callback: Optional[Callable] = None, + iterations: int = 1, **keyword_args, - )->Iterator[InvokeAIGeneratorOutput]: - ''' + ) -> Iterator[InvokeAIGeneratorOutput]: + """ Return an iterator across the indicated number of generations. Each time the iterator is called it will return an InvokeAIGeneratorOutput object. Use like this: @@ -107,7 +112,7 @@ class InvokeAIGenerator(metaclass=ABCMeta): for o in outputs: print(o.image, o.seed) - ''' + """ generator_args = dataclasses.asdict(self.params) generator_args.update(keyword_args) @@ -118,22 +123,21 @@ class InvokeAIGenerator(metaclass=ABCMeta): gen_class = self._generator_class() generator = gen_class(model, self.params.precision, **self.kwargs) if self.params.variation_amount > 0: - generator.set_variation(generator_args.get('seed'), - generator_args.get('variation_amount'), - generator_args.get('with_variations') - ) + generator.set_variation( + generator_args.get("seed"), + generator_args.get("variation_amount"), + generator_args.get("with_variations"), + ) if isinstance(model, DiffusionPipeline): for component in [model.unet, model.vae]: - configure_model_padding(component, - generator_args.get('seamless',False), - generator_args.get('seamless_axes') - ) + configure_model_padding( + component, generator_args.get("seamless", False), generator_args.get("seamless_axes") + ) else: - configure_model_padding(model, - generator_args.get('seamless',False), - generator_args.get('seamless_axes') - ) + configure_model_padding( + model, generator_args.get("seamless", False), generator_args.get("seamless_axes") + ) iteration_count = range(iterations) if iterations else itertools.count(start=0, step=1) for i in iteration_count: @@ -147,66 +151,66 @@ class InvokeAIGenerator(metaclass=ABCMeta): image=results[0][0], seed=results[0][1], attention_maps_images=results[0][2], - model_hash = model_hash, - params=Namespace(model_name=model_name,**generator_args), + model_hash=model_hash, + params=Namespace(model_name=model_name, **generator_args), ) if callback: callback(output) yield output @classmethod - def schedulers(self)->List[str]: - ''' + def schedulers(self) -> List[str]: + """ Return list of all the schedulers that we currently handle. - ''' + """ return list(SCHEDULER_MAP.keys()) def load_generator(self, model: StableDiffusionGeneratorPipeline, generator_class: Type[Generator]): return generator_class(model, self.params.precision) @classmethod - def _generator_class(cls)->Type[Generator]: - ''' + def _generator_class(cls) -> Type[Generator]: + """ In derived classes return the name of the generator to apply. If you don't override will return the name of the derived class, which nicely parallels the generator class names. - ''' + """ return Generator + # ------------------------------------ class Img2Img(InvokeAIGenerator): - def generate(self, - init_image: Union[Image.Image, torch.FloatTensor], - strength: float=0.75, - **keyword_args - )->Iterator[InvokeAIGeneratorOutput]: - return super().generate(init_image=init_image, - strength=strength, - **keyword_args - ) + def generate( + self, init_image: Union[Image.Image, torch.FloatTensor], strength: float = 0.75, **keyword_args + ) -> Iterator[InvokeAIGeneratorOutput]: + return super().generate(init_image=init_image, strength=strength, **keyword_args) + @classmethod def _generator_class(cls): from .img2img import Img2Img + return Img2Img + # ------------------------------------ # Takes all the arguments of Img2Img and adds the mask image and the seam/infill stuff class Inpaint(Img2Img): - def generate(self, - mask_image: Union[Image.Image, torch.FloatTensor], - # Seam settings - when 0, doesn't fill seam - seam_size: int = 96, - seam_blur: int = 16, - seam_strength: float = 0.7, - seam_steps: int = 30, - tile_size: int = 32, - inpaint_replace=False, - infill_method=None, - inpaint_width=None, - inpaint_height=None, - inpaint_fill: tuple(int) = (0x7F, 0x7F, 0x7F, 0xFF), - **keyword_args - )->Iterator[InvokeAIGeneratorOutput]: + def generate( + self, + mask_image: Union[Image.Image, torch.FloatTensor], + # Seam settings - when 0, doesn't fill seam + seam_size: int = 96, + seam_blur: int = 16, + seam_strength: float = 0.7, + seam_steps: int = 30, + tile_size: int = 32, + inpaint_replace=False, + infill_method=None, + inpaint_width=None, + inpaint_height=None, + inpaint_fill: tuple(int) = (0x7F, 0x7F, 0x7F, 0xFF), + **keyword_args, + ) -> Iterator[InvokeAIGeneratorOutput]: return super().generate( mask_image=mask_image, seam_size=seam_size, @@ -219,13 +223,16 @@ class Inpaint(Img2Img): inpaint_width=inpaint_width, inpaint_height=inpaint_height, inpaint_fill=inpaint_fill, - **keyword_args + **keyword_args, ) + @classmethod def _generator_class(cls): from .inpaint import Inpaint + return Inpaint + class Generator: downsampling_factor: int latent_channels: int @@ -251,9 +258,7 @@ class Generator: Returns a function returning an image derived from the prompt and the initial image Return value depends on the seed at the time you call it """ - raise NotImplementedError( - "image_iterator() must be implemented in a descendent class" - ) + raise NotImplementedError("image_iterator() must be implemented in a descendent class") def set_variation(self, seed, variation_amount, with_variations): self.seed = seed @@ -280,9 +285,7 @@ class Generator: scope = nullcontext self.free_gpu_mem = free_gpu_mem attention_maps_images = [] - attention_maps_callback = lambda saver: attention_maps_images.append( - saver.get_stacked_maps_image() - ) + attention_maps_callback = lambda saver: attention_maps_images.append(saver.get_stacked_maps_image()) make_image = self.get_make_image( sampler=sampler, init_image=init_image, @@ -327,11 +330,7 @@ class Generator: results.append([image, seed, attention_maps_images]) if image_callback is not None: - attention_maps_image = ( - None - if len(attention_maps_images) == 0 - else attention_maps_images[-1] - ) + attention_maps_image = None if len(attention_maps_images) == 0 else attention_maps_images[-1] image_callback( image, seed, @@ -342,9 +341,7 @@ class Generator: seed = self.new_seed() # Free up memory from the last generation. - clear_cuda_cache = ( - kwargs["clear_cuda_cache"] if "clear_cuda_cache" in kwargs else None - ) + clear_cuda_cache = kwargs["clear_cuda_cache"] if "clear_cuda_cache" in kwargs else None if clear_cuda_cache is not None: clear_cuda_cache() @@ -371,14 +368,8 @@ class Generator: # Get the original alpha channel of the mask if there is one. # Otherwise it is some other black/white image format ('1', 'L' or 'RGB') - pil_init_mask = ( - init_mask.getchannel("A") - if init_mask.mode == "RGBA" - else init_mask.convert("L") - ) - pil_init_image = init_image.convert( - "RGBA" - ) # Add an alpha channel if one doesn't exist + pil_init_mask = init_mask.getchannel("A") if init_mask.mode == "RGBA" else init_mask.convert("L") + pil_init_image = init_image.convert("RGBA") # Add an alpha channel if one doesn't exist # Build an image with only visible pixels from source to use as reference for color-matching. init_rgb_pixels = np.asarray(init_image.convert("RGB"), dtype=np.uint8) @@ -404,10 +395,7 @@ class Generator: np_matched_result[:, :, :] = ( ( ( - ( - np_matched_result[:, :, :].astype(np.float32) - - gen_means[None, None, :] - ) + (np_matched_result[:, :, :].astype(np.float32) - gen_means[None, None, :]) / gen_std[None, None, :] ) * init_std[None, None, :] @@ -433,9 +421,7 @@ class Generator: else: blurred_init_mask = pil_init_mask - multiplied_blurred_init_mask = ImageChops.multiply( - blurred_init_mask, self.pil_image.split()[-1] - ) + multiplied_blurred_init_mask = ImageChops.multiply(blurred_init_mask, self.pil_image.split()[-1]) # Paste original on color-corrected generation (using blurred mask) matched_result.paste(init_image, (0, 0), mask=multiplied_blurred_init_mask) @@ -461,10 +447,7 @@ class Generator: latent_image = samples[0].permute(1, 2, 0) @ v1_5_latent_rgb_factors latents_ubyte = ( - ((latent_image + 1) / 2) - .clamp(0, 1) # change scale from -1..1 to 0..1 - .mul(0xFF) # to 0..255 - .byte() + ((latent_image + 1) / 2).clamp(0, 1).mul(0xFF).byte() # change scale from -1..1 to 0..1 # to 0..255 ).cpu() return Image.fromarray(latents_ubyte.numpy()) @@ -494,9 +477,7 @@ class Generator: temp_height = int((height + 7) / 8) * 8 noise = torch.stack( [ - rand_perlin_2d( - (temp_height, temp_width), (8, 8), device=self.model.device - ).to(fixdevice) + rand_perlin_2d((temp_height, temp_width), (8, 8), device=self.model.device).to(fixdevice) for _ in range(input_channels) ], dim=0, @@ -573,8 +554,6 @@ class Generator: device=device, ) if self.perlin > 0.0: - perlin_noise = self.get_perlin_noise( - width // self.downsampling_factor, height // self.downsampling_factor - ) + perlin_noise = self.get_perlin_noise(width // self.downsampling_factor, height // self.downsampling_factor) x = (1 - self.perlin) * x + self.perlin * perlin_noise return x diff --git a/invokeai/backend/generator/img2img.py b/invokeai/backend/generator/img2img.py index b3b0e8f510..5490b2325c 100644 --- a/invokeai/backend/generator/img2img.py +++ b/invokeai/backend/generator/img2img.py @@ -77,10 +77,7 @@ class Img2Img(Generator): callback=step_callback, seed=seed, ) - if ( - pipeline_output.attention_map_saver is not None - and attention_maps_callback is not None - ): + if pipeline_output.attention_map_saver is not None and attention_maps_callback is not None: attention_maps_callback(pipeline_output.attention_map_saver) return pipeline.numpy_to_pil(pipeline_output.images)[0] @@ -91,7 +88,5 @@ class Img2Img(Generator): x = torch.randn_like(like, device=device) if self.perlin > 0.0: shape = like.shape - x = (1 - self.perlin) * x + self.perlin * self.get_perlin_noise( - shape[3], shape[2] - ) + x = (1 - self.perlin) * x + self.perlin * self.get_perlin_noise(shape[3], shape[2]) return x diff --git a/invokeai/backend/generator/inpaint.py b/invokeai/backend/generator/inpaint.py index c91fe0c6a7..7aeb3d4809 100644 --- a/invokeai/backend/generator/inpaint.py +++ b/invokeai/backend/generator/inpaint.py @@ -68,15 +68,11 @@ class Inpaint(Img2Img): return im # Patchmatch (note, we may want to expose patch_size? Increasing it significantly impacts performance though) - im_patched_np = PatchMatch.inpaint( - im.convert("RGB"), ImageOps.invert(im.split()[-1]), patch_size=3 - ) + im_patched_np = PatchMatch.inpaint(im.convert("RGB"), ImageOps.invert(im.split()[-1]), patch_size=3) im_patched = Image.fromarray(im_patched_np, mode="RGB") return im_patched - def tile_fill_missing( - self, im: Image.Image, tile_size: int = 16, seed: Optional[int] = None - ) -> Image.Image: + def tile_fill_missing(self, im: Image.Image, tile_size: int = 16, seed: Optional[int] = None) -> Image.Image: # Only fill if there's an alpha layer if im.mode != "RGBA": return im @@ -127,15 +123,11 @@ class Inpaint(Img2Img): return si - def mask_edge( - self, mask: Image.Image, edge_size: int, edge_blur: int - ) -> Image.Image: + def mask_edge(self, mask: Image.Image, edge_size: int, edge_blur: int) -> Image.Image: npimg = np.asarray(mask, dtype=np.uint8) # Detect any partially transparent regions - npgradient = np.uint8( - 255 * (1.0 - np.floor(np.abs(0.5 - np.float32(npimg) / 255.0) * 2.0)) - ) + npgradient = np.uint8(255 * (1.0 - np.floor(np.abs(0.5 - np.float32(npimg) / 255.0) * 2.0))) # Detect hard edges npedge = cv2.Canny(npimg, threshold1=100, threshold2=200) @@ -144,9 +136,7 @@ class Inpaint(Img2Img): npmask = npgradient + npedge # Expand - npmask = cv2.dilate( - npmask, np.ones((3, 3), np.uint8), iterations=int(edge_size / 2) - ) + npmask = cv2.dilate(npmask, np.ones((3, 3), np.uint8), iterations=int(edge_size / 2)) new_mask = Image.fromarray(npmask) @@ -242,25 +232,19 @@ class Inpaint(Img2Img): if infill_method == "patchmatch" and PatchMatch.patchmatch_available(): init_filled = self.infill_patchmatch(self.pil_image.copy()) elif infill_method == "tile": - init_filled = self.tile_fill_missing( - self.pil_image.copy(), seed=self.seed, tile_size=tile_size - ) + init_filled = self.tile_fill_missing(self.pil_image.copy(), seed=self.seed, tile_size=tile_size) elif infill_method == "solid": solid_bg = Image.new("RGBA", init_image.size, inpaint_fill) init_filled = Image.alpha_composite(solid_bg, init_image) else: - raise ValueError( - f"Non-supported infill type {infill_method}", infill_method - ) + raise ValueError(f"Non-supported infill type {infill_method}", infill_method) init_filled.paste(init_image, (0, 0), init_image.split()[-1]) # Resize if requested for inpainting if inpaint_width and inpaint_height: init_filled = init_filled.resize((inpaint_width, inpaint_height)) - debug_image( - init_filled, "init_filled", debug_status=self.enable_image_debugging - ) + debug_image(init_filled, "init_filled", debug_status=self.enable_image_debugging) # Create init tensor init_image = image_resized_to_grid_as_tensor(init_filled.convert("RGB")) @@ -289,9 +273,7 @@ class Inpaint(Img2Img): "mask_image AFTER multiply with pil_image", debug_status=self.enable_image_debugging, ) - mask: torch.FloatTensor = image_resized_to_grid_as_tensor( - mask_image, normalize=False - ) + mask: torch.FloatTensor = image_resized_to_grid_as_tensor(mask_image, normalize=False) else: mask: torch.FloatTensor = mask_image @@ -302,9 +284,9 @@ class Inpaint(Img2Img): # todo: support cross-attention control uc, c, _ = conditioning - conditioning_data = ConditioningData( - uc, c, cfg_scale - ).add_scheduler_args_if_applicable(pipeline.scheduler, eta=ddim_eta) + conditioning_data = ConditioningData(uc, c, cfg_scale).add_scheduler_args_if_applicable( + pipeline.scheduler, eta=ddim_eta + ) def make_image(x_T: torch.Tensor, seed: int): pipeline_output = pipeline.inpaint_from_embeddings( @@ -318,15 +300,10 @@ class Inpaint(Img2Img): seed=seed, ) - if ( - pipeline_output.attention_map_saver is not None - and attention_maps_callback is not None - ): + if pipeline_output.attention_map_saver is not None and attention_maps_callback is not None: attention_maps_callback(pipeline_output.attention_map_saver) - result = self.postprocess_size_and_mask( - pipeline.numpy_to_pil(pipeline_output.images)[0] - ) + result = self.postprocess_size_and_mask(pipeline.numpy_to_pil(pipeline_output.images)[0]) # Seam paint if this is our first pass (seam_size set to 0 during seam painting) if seam_size > 0: diff --git a/invokeai/backend/image_util/__init__.py b/invokeai/backend/image_util/__init__.py index 410f003f6a..9fa635b389 100644 --- a/invokeai/backend/image_util/__init__.py +++ b/invokeai/backend/image_util/__init__.py @@ -8,9 +8,7 @@ from .txt2mask import Txt2Mask from .util import InitImageResizer, make_grid -def debug_image( - debug_image, debug_text, debug_show=True, debug_result=False, debug_status=False -): +def debug_image(debug_image, debug_text, debug_show=True, debug_result=False, debug_status=False): if not debug_status: return diff --git a/invokeai/backend/image_util/invisible_watermark.py b/invokeai/backend/image_util/invisible_watermark.py index 0fb72b095d..4605daea43 100644 --- a/invokeai/backend/image_util/invisible_watermark.py +++ b/invokeai/backend/image_util/invisible_watermark.py @@ -9,26 +9,26 @@ from PIL import Image from imwatermark import WatermarkEncoder from invokeai.app.services.config import InvokeAIAppConfig import invokeai.backend.util.logging as logger + config = InvokeAIAppConfig.get_config() + class InvisibleWatermark: """ Wrapper around InvisibleWatermark module. """ - + @classmethod def invisible_watermark_available(self) -> bool: return config.invisible_watermark @classmethod - def add_watermark(self, image: Image, watermark_text:str) -> Image: + def add_watermark(self, image: Image, watermark_text: str) -> Image: if not self.invisible_watermark_available(): return image logger.debug(f'Applying invisible watermark "{watermark_text}"') bgr = cv2.cvtColor(np.array(image.convert("RGB")), cv2.COLOR_RGB2BGR) encoder = WatermarkEncoder() - encoder.set_watermark('bytes', watermark_text.encode('utf-8')) - bgr_encoded = encoder.encode(bgr, 'dwtDct') - return Image.fromarray( - cv2.cvtColor(bgr_encoded, cv2.COLOR_BGR2RGB) - ).convert("RGBA") + encoder.set_watermark("bytes", watermark_text.encode("utf-8")) + bgr_encoded = encoder.encode(bgr, "dwtDct") + return Image.fromarray(cv2.cvtColor(bgr_encoded, cv2.COLOR_BGR2RGB)).convert("RGBA") diff --git a/invokeai/backend/image_util/patchmatch.py b/invokeai/backend/image_util/patchmatch.py index 2e65f08d9f..98055f60c8 100644 --- a/invokeai/backend/image_util/patchmatch.py +++ b/invokeai/backend/image_util/patchmatch.py @@ -7,8 +7,10 @@ be suppressed or deferred import numpy as np import invokeai.backend.util.logging as logger from invokeai.app.services.config import InvokeAIAppConfig + config = InvokeAIAppConfig.get_config() + class PatchMatch: """ Thin class wrapper around the patchmatch function. diff --git a/invokeai/backend/image_util/pngwriter.py b/invokeai/backend/image_util/pngwriter.py index 452bbfc783..d3f53d7e72 100644 --- a/invokeai/backend/image_util/pngwriter.py +++ b/invokeai/backend/image_util/pngwriter.py @@ -34,9 +34,7 @@ class PngWriter: # saves image named _image_ to outdir/name, writing metadata from prompt # returns full path of output - def save_image_and_prompt_to_png( - self, image, dream_prompt, name, metadata=None, compress_level=6 - ): + def save_image_and_prompt_to_png(self, image, dream_prompt, name, metadata=None, compress_level=6): path = os.path.join(self.outdir, name) info = PngImagePlugin.PngInfo() info.add_text("Dream", dream_prompt) @@ -114,8 +112,6 @@ class PromptFormatter: if opt.variation_amount > 0: switches.append(f"-v{opt.variation_amount}") if opt.with_variations: - formatted_variations = ",".join( - f"{seed}:{weight}" for seed, weight in opt.with_variations - ) + formatted_variations = ",".join(f"{seed}:{weight}" for seed, weight in opt.with_variations) switches.append(f"-V{formatted_variations}") return " ".join(switches) diff --git a/invokeai/backend/image_util/safety_checker.py b/invokeai/backend/image_util/safety_checker.py index 7a31c9422d..483e563b82 100644 --- a/invokeai/backend/image_util/safety_checker.py +++ b/invokeai/backend/image_util/safety_checker.py @@ -9,14 +9,17 @@ from invokeai.backend import SilenceWarnings from invokeai.app.services.config import InvokeAIAppConfig from invokeai.backend.util.devices import choose_torch_device import invokeai.backend.util.logging as logger + config = InvokeAIAppConfig.get_config() -CHECKER_PATH = 'core/convert/stable-diffusion-safety-checker' +CHECKER_PATH = "core/convert/stable-diffusion-safety-checker" + class SafetyChecker: """ Wrapper around SafetyChecker model. """ + safety_checker = None feature_extractor = None tried_load: bool = False @@ -25,21 +28,19 @@ class SafetyChecker: def _load_safety_checker(self): if self.tried_load: return - + if config.nsfw_checker: try: from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from transformers import AutoFeatureExtractor - self.safety_checker = StableDiffusionSafetyChecker.from_pretrained( - config.models_path / CHECKER_PATH - ) - self.feature_extractor = AutoFeatureExtractor.from_pretrained( - config.models_path / CHECKER_PATH) - logger.info('NSFW checker initialized') + + self.safety_checker = StableDiffusionSafetyChecker.from_pretrained(config.models_path / CHECKER_PATH) + self.feature_extractor = AutoFeatureExtractor.from_pretrained(config.models_path / CHECKER_PATH) + logger.info("NSFW checker initialized") except Exception as e: - logger.warning(f'Could not load NSFW checker: {str(e)}') + logger.warning(f"Could not load NSFW checker: {str(e)}") else: - logger.info('NSFW checker loading disabled') + logger.info("NSFW checker loading disabled") self.tried_load = True @classmethod @@ -51,7 +52,7 @@ class SafetyChecker: def has_nsfw_concept(self, image: Image) -> bool: if not self.safety_checker_available(): return False - + device = choose_torch_device() features = self.feature_extractor([image], return_tensors="pt") features.to(device) diff --git a/invokeai/backend/image_util/seamless.py b/invokeai/backend/image_util/seamless.py index 4fbc0cd78e..6fb2617901 100644 --- a/invokeai/backend/image_util/seamless.py +++ b/invokeai/backend/image_util/seamless.py @@ -5,12 +5,8 @@ def _conv_forward_asymmetric(self, input, weight, bias): """ Patch for Conv2d._conv_forward that supports asymmetric padding """ - working = nn.functional.pad( - input, self.asymmetric_padding["x"], mode=self.asymmetric_padding_mode["x"] - ) - working = nn.functional.pad( - working, self.asymmetric_padding["y"], mode=self.asymmetric_padding_mode["y"] - ) + working = nn.functional.pad(input, self.asymmetric_padding["x"], mode=self.asymmetric_padding_mode["x"]) + working = nn.functional.pad(working, self.asymmetric_padding["y"], mode=self.asymmetric_padding_mode["y"]) return nn.functional.conv2d( working, weight, @@ -32,18 +28,14 @@ def configure_model_padding(model, seamless, seamless_axes): if seamless: m.asymmetric_padding_mode = {} m.asymmetric_padding = {} - m.asymmetric_padding_mode["x"] = ( - "circular" if ("x" in seamless_axes) else "constant" - ) + m.asymmetric_padding_mode["x"] = "circular" if ("x" in seamless_axes) else "constant" m.asymmetric_padding["x"] = ( m._reversed_padding_repeated_twice[0], m._reversed_padding_repeated_twice[1], 0, 0, ) - m.asymmetric_padding_mode["y"] = ( - "circular" if ("y" in seamless_axes) else "constant" - ) + m.asymmetric_padding_mode["y"] = "circular" if ("y" in seamless_axes) else "constant" m.asymmetric_padding["y"] = ( 0, 0, diff --git a/invokeai/backend/image_util/txt2mask.py b/invokeai/backend/image_util/txt2mask.py index 429c9b63fb..12db54b0db 100644 --- a/invokeai/backend/image_util/txt2mask.py +++ b/invokeai/backend/image_util/txt2mask.py @@ -39,23 +39,18 @@ CLIPSEG_MODEL = "CIDAS/clipseg-rd64-refined" CLIPSEG_SIZE = 352 config = InvokeAIAppConfig.get_config() + class SegmentedGrayscale(object): def __init__(self, image: Image, heatmap: torch.Tensor): self.heatmap = heatmap self.image = image def to_grayscale(self, invert: bool = False) -> Image: - return self._rescale( - Image.fromarray( - np.uint8(255 - self.heatmap * 255 if invert else self.heatmap * 255) - ) - ) + return self._rescale(Image.fromarray(np.uint8(255 - self.heatmap * 255 if invert else self.heatmap * 255))) def to_mask(self, threshold: float = 0.5) -> Image: discrete_heatmap = self.heatmap.lt(threshold).int() - return self._rescale( - Image.fromarray(np.uint8(discrete_heatmap * 255), mode="L") - ) + return self._rescale(Image.fromarray(np.uint8(discrete_heatmap * 255), mode="L")) def to_transparent(self, invert: bool = False) -> Image: transparent_image = self.image.copy() @@ -67,11 +62,7 @@ class SegmentedGrayscale(object): # unscales and uncrops the 352x352 heatmap so that it matches the image again def _rescale(self, heatmap: Image) -> Image: - size = ( - self.image.width - if (self.image.width > self.image.height) - else self.image.height - ) + size = self.image.width if (self.image.width > self.image.height) else self.image.height resized_image = heatmap.resize((size, size), resample=Image.Resampling.LANCZOS) return resized_image.crop((0, 0, self.image.width, self.image.height)) @@ -87,12 +78,8 @@ class Txt2Mask(object): # BUG: we are not doing anything with the device option at this time self.device = device - self.processor = AutoProcessor.from_pretrained( - CLIPSEG_MODEL, cache_dir=config.cache_dir - ) - self.model = CLIPSegForImageSegmentation.from_pretrained( - CLIPSEG_MODEL, cache_dir=config.cache_dir - ) + self.processor = AutoProcessor.from_pretrained(CLIPSEG_MODEL, cache_dir=config.cache_dir) + self.model = CLIPSegForImageSegmentation.from_pretrained(CLIPSEG_MODEL, cache_dir=config.cache_dir) @torch.no_grad() def segment(self, image, prompt: str) -> SegmentedGrayscale: @@ -107,9 +94,7 @@ class Txt2Mask(object): image = ImageOps.exif_transpose(image) img = self._scale_and_crop(image) - inputs = self.processor( - text=[prompt], images=[img], padding=True, return_tensors="pt" - ) + inputs = self.processor(text=[prompt], images=[img], padding=True, return_tensors="pt") outputs = self.model(**inputs) heatmap = torch.sigmoid(outputs.logits) return SegmentedGrayscale(image, heatmap) diff --git a/invokeai/backend/install/check_root.py b/invokeai/backend/install/check_root.py index 0c24034dc7..ded9e66635 100644 --- a/invokeai/backend/install/check_root.py +++ b/invokeai/backend/install/check_root.py @@ -6,26 +6,31 @@ from invokeai.app.services.config import ( InvokeAIAppConfig, ) + def check_invokeai_root(config: InvokeAIAppConfig): try: - assert config.model_conf_path.exists() - assert config.db_path.exists() - assert config.models_path.exists() + assert config.model_conf_path.exists(), f"{config.model_conf_path} not found" + assert config.db_path.parent.exists(), f"{config.db_path.parent} not found" + assert config.models_path.exists(), f"{config.models_path} not found" for model in [ - 'CLIP-ViT-bigG-14-laion2B-39B-b160k', - 'bert-base-uncased', - 'clip-vit-large-patch14', - 'sd-vae-ft-mse', - 'stable-diffusion-2-clip', - 'stable-diffusion-safety-checker']: - assert (config.models_path / f'core/convert/{model}').exists() - except: + "CLIP-ViT-bigG-14-laion2B-39B-b160k", + "bert-base-uncased", + "clip-vit-large-patch14", + "sd-vae-ft-mse", + "stable-diffusion-2-clip", + "stable-diffusion-safety-checker", + ]: + path = config.models_path / f"core/convert/{model}" + assert path.exists(), f"{path} is missing" + except Exception as e: print() - print('== STARTUP ABORTED ==') - print('** One or more necessary files is missing from your InvokeAI root directory **') - print('** Please rerun the configuration script to fix this problem. **') - print('** From the launcher, selection option [7]. **') - print('** From the command line, activate the virtual environment and run "invokeai-configure --yes --skip-sd-weights" **') - input('Press any key to continue...') + print(f"An exception has occurred: {str(e)}") + print("== STARTUP ABORTED ==") + print("** One or more necessary files is missing from your InvokeAI root directory **") + print("** Please rerun the configuration script to fix this problem. **") + print("** From the launcher, selection option [7]. **") + print( + '** From the command line, activate the virtual environment and run "invokeai-configure --yes --skip-sd-weights" **' + ) + input("Press any key to continue...") sys.exit(0) - diff --git a/invokeai/backend/install/invokeai_configure.py b/invokeai/backend/install/invokeai_configure.py index 0d3f98155c..972e6668c4 100755 --- a/invokeai/backend/install/invokeai_configure.py +++ b/invokeai/backend/install/invokeai_configure.py @@ -13,8 +13,8 @@ import os import shutil import textwrap import traceback -import warnings import yaml +import warnings from argparse import Namespace from pathlib import Path from shutil import get_terminal_size @@ -45,6 +45,7 @@ from invokeai.app.services.config import ( from invokeai.backend.util.logging import InvokeAILogger from invokeai.frontend.install.model_install import addModelsForm, process_and_execute from invokeai.frontend.install.widgets import ( + SingleSelectColumns, CenteredButtonPress, FileBox, IntTitleSlider, @@ -56,13 +57,10 @@ from invokeai.frontend.install.widgets import ( from invokeai.backend.install.legacy_arg_parsing import legacy_parser from invokeai.backend.install.model_install_backend import ( hf_download_from_pretrained, - hf_download_with_resume, InstallSelections, ModelInstall, ) -from invokeai.backend.model_management.model_probe import ( - ModelType, BaseModelType - ) +from invokeai.backend.model_management.model_probe import ModelType, BaseModelType warnings.filterwarnings("ignore") transformers.logging.set_verbosity_error() @@ -77,7 +75,7 @@ Model_dir = "models" Default_config_file = config.model_conf_path SD_Configs = config.legacy_conf_path -PRECISION_CHOICES = ['auto','float16','float32'] +PRECISION_CHOICES = ["auto", "float16", "float32"] INIT_FILE_PREAMBLE = """# InvokeAI initialization file # This is the InvokeAI initialization file, which contains command-line default values. @@ -85,7 +83,8 @@ INIT_FILE_PREAMBLE = """# InvokeAI initialization file # or renaming it and then running invokeai-configure again. """ -logger=InvokeAILogger.getLogger() +logger = InvokeAILogger.getLogger() + # -------------------------------------------- def postscript(errors: None): @@ -108,7 +107,9 @@ Add the '--help' argument to see all of the command-line switches available for """ else: - message = "\n** There were errors during installation. It is possible some of the models were not fully downloaded.\n" + message = ( + "\n** There were errors during installation. It is possible some of the models were not fully downloaded.\n" + ) for err in errors: message += f"\t - {err}\n" message += "Please check the logs above and correct any issues." @@ -169,9 +170,7 @@ def download_with_progress_bar(model_url: str, model_dest: str, label: str = "th logger.info(f"Installing {label} model file {model_url}...") if not os.path.exists(model_dest): os.makedirs(os.path.dirname(model_dest), exist_ok=True) - request.urlretrieve( - model_url, model_dest, ProgressBar(os.path.basename(model_dest)) - ) + request.urlretrieve(model_url, model_dest, ProgressBar(os.path.basename(model_dest))) logger.info("...downloaded successfully") else: logger.info("...exists") @@ -182,90 +181,93 @@ def download_with_progress_bar(model_url: str, model_dest: str, label: str = "th def download_conversion_models(): - target_dir = config.root_path / 'models/core/convert' + target_dir = config.root_path / "models/core/convert" kwargs = dict() # for future use try: - logger.info('Downloading core tokenizers and text encoders') + logger.info("Downloading core tokenizers and text encoders") # bert with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) bert = BertTokenizerFast.from_pretrained("bert-base-uncased", **kwargs) - bert.save_pretrained(target_dir / 'bert-base-uncased', safe_serialization=True) - + bert.save_pretrained(target_dir / "bert-base-uncased", safe_serialization=True) + # sd-1 - repo_id = 'openai/clip-vit-large-patch14' - hf_download_from_pretrained(CLIPTokenizer, repo_id, target_dir / 'clip-vit-large-patch14') - hf_download_from_pretrained(CLIPTextModel, repo_id, target_dir / 'clip-vit-large-patch14') + repo_id = "openai/clip-vit-large-patch14" + hf_download_from_pretrained(CLIPTokenizer, repo_id, target_dir / "clip-vit-large-patch14") + hf_download_from_pretrained(CLIPTextModel, repo_id, target_dir / "clip-vit-large-patch14") # sd-2 repo_id = "stabilityai/stable-diffusion-2" pipeline = CLIPTokenizer.from_pretrained(repo_id, subfolder="tokenizer", **kwargs) - pipeline.save_pretrained(target_dir / 'stable-diffusion-2-clip' / 'tokenizer', safe_serialization=True) + pipeline.save_pretrained(target_dir / "stable-diffusion-2-clip" / "tokenizer", safe_serialization=True) pipeline = CLIPTextModel.from_pretrained(repo_id, subfolder="text_encoder", **kwargs) - pipeline.save_pretrained(target_dir / 'stable-diffusion-2-clip' / 'text_encoder', safe_serialization=True) + pipeline.save_pretrained(target_dir / "stable-diffusion-2-clip" / "text_encoder", safe_serialization=True) # sd-xl - tokenizer_2 repo_id = "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k" - _, model_name = repo_id.split('/') + _, model_name = repo_id.split("/") pipeline = CLIPTokenizer.from_pretrained(repo_id, **kwargs) pipeline.save_pretrained(target_dir / model_name, safe_serialization=True) - + pipeline = CLIPTextConfig.from_pretrained(repo_id, **kwargs) pipeline.save_pretrained(target_dir / model_name, safe_serialization=True) - + # VAE - logger.info('Downloading stable diffusion VAE') - vae = AutoencoderKL.from_pretrained('stabilityai/sd-vae-ft-mse', **kwargs) - vae.save_pretrained(target_dir / 'sd-vae-ft-mse', safe_serialization=True) + logger.info("Downloading stable diffusion VAE") + vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", **kwargs) + vae.save_pretrained(target_dir / "sd-vae-ft-mse", safe_serialization=True) # safety checking - logger.info('Downloading safety checker') + logger.info("Downloading safety checker") repo_id = "CompVis/stable-diffusion-safety-checker" - pipeline = AutoFeatureExtractor.from_pretrained(repo_id,**kwargs) - pipeline.save_pretrained(target_dir / 'stable-diffusion-safety-checker', safe_serialization=True) + pipeline = AutoFeatureExtractor.from_pretrained(repo_id, **kwargs) + pipeline.save_pretrained(target_dir / "stable-diffusion-safety-checker", safe_serialization=True) - pipeline = StableDiffusionSafetyChecker.from_pretrained(repo_id,**kwargs) - pipeline.save_pretrained(target_dir / 'stable-diffusion-safety-checker', safe_serialization=True) + pipeline = StableDiffusionSafetyChecker.from_pretrained(repo_id, **kwargs) + pipeline.save_pretrained(target_dir / "stable-diffusion-safety-checker", safe_serialization=True) except KeyboardInterrupt: raise except Exception as e: logger.error(str(e)) + # --------------------------------------------- def download_realesrgan(): logger.info("Installing ESRGAN Upscaling models...") URLs = [ dict( - url = "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth", - dest = "core/upscaling/realesrgan/RealESRGAN_x4plus.pth", - description = "RealESRGAN_x4plus.pth", + url="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth", + dest="core/upscaling/realesrgan/RealESRGAN_x4plus.pth", + description="RealESRGAN_x4plus.pth", ), dict( - url = "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth", - dest = "core/upscaling/realesrgan/RealESRGAN_x4plus_anime_6B.pth", - description = "RealESRGAN_x4plus_anime_6B.pth", + url="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth", + dest="core/upscaling/realesrgan/RealESRGAN_x4plus_anime_6B.pth", + description="RealESRGAN_x4plus_anime_6B.pth", ), dict( - url= "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth", - dest= "core/upscaling/realesrgan/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth", - description = "ESRGAN_SRx4_DF2KOST_official.pth", + url="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth", + dest="core/upscaling/realesrgan/ESRGAN_SRx4_DF2KOST_official-ff704c30.pth", + description="ESRGAN_SRx4_DF2KOST_official.pth", ), dict( - url= "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth", - dest= "core/upscaling/realesrgan/RealESRGAN_x2plus.pth", - description = "RealESRGAN_x2plus.pth", + url="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth", + dest="core/upscaling/realesrgan/RealESRGAN_x2plus.pth", + description="RealESRGAN_x2plus.pth", ), ] for model in URLs: - download_with_progress_bar(model['url'], config.models_path / model['dest'], model['description']) + download_with_progress_bar(model["url"], config.models_path / model["dest"], model["description"]) + # --------------------------------------------- def download_support_models(): download_realesrgan() download_conversion_models() + # ------------------------------------- def get_root(root: str = None) -> str: if root: @@ -275,6 +277,7 @@ def get_root(root: str = None) -> str: else: return str(config.root_path) + # ------------------------------------- class editOptsForm(CyclingForm, npyscreen.FormMultiPage): # for responsive resizing - disabled @@ -283,14 +286,14 @@ class editOptsForm(CyclingForm, npyscreen.FormMultiPage): def create(self): program_opts = self.parentApp.program_opts old_opts = self.parentApp.invokeai_opts - first_time = not (config.root_path / 'invokeai.yaml').exists() + first_time = not (config.root_path / "invokeai.yaml").exists() access_token = HfFolder.get_token() window_width, window_height = get_terminal_size() label = """Configure startup settings. You can come back and change these later. Use ctrl-N and ctrl-P to move to the ext and

revious fields. Use cursor arrows to make a checkbox selection, and space to toggle. """ - for i in textwrap.wrap(label,width=window_width-6): + for i in textwrap.wrap(label, width=window_width - 6): self.add_widget_intelligent( npyscreen.FixedText, value=i, @@ -300,7 +303,7 @@ Use cursor arrows to make a checkbox selection, and space to toggle. self.nextrely += 1 label = """HuggingFace access token (OPTIONAL) for automatic model downloads. See https://huggingface.co/settings/tokens.""" - for line in textwrap.wrap(label,width=window_width-6): + for line in textwrap.wrap(label, width=window_width - 6): self.add_widget_intelligent( npyscreen.FixedText, value=line, @@ -330,34 +333,47 @@ Use cursor arrows to make a checkbox selection, and space to toggle. npyscreen.Checkbox, name="Free GPU memory after each generation", value=old_opts.free_gpu_mem, + max_width=45, relx=5, scroll_exit=True, ) + self.nextrely -= 1 self.xformers_enabled = self.add_widget_intelligent( npyscreen.Checkbox, - name="Enable xformers support if available", + name="Enable xformers support", value=old_opts.xformers_enabled, - relx=5, + max_width=30, + relx=50, scroll_exit=True, ) + self.nextrely -= 1 self.always_use_cpu = self.add_widget_intelligent( npyscreen.Checkbox, name="Force CPU to be used on GPU systems", value=old_opts.always_use_cpu, - relx=5, + relx=80, scroll_exit=True, ) - precision = old_opts.precision or ( - "float32" if program_opts.full_precision else "auto" + precision = old_opts.precision or ("float32" if program_opts.full_precision else "auto") + self.nextrely += 1 + self.add_widget_intelligent( + npyscreen.TitleFixedText, + name="Floating Point Precision", + begin_entry_at=0, + editable=False, + color="CONTROL", + scroll_exit=True, ) + self.nextrely -= 1 self.precision = self.add_widget_intelligent( - npyscreen.TitleSelectOne, - columns = 2, + SingleSelectColumns, + columns=3, name="Precision", values=PRECISION_CHOICES, value=PRECISION_CHOICES.index(precision), begin_entry_at=3, - max_height=len(PRECISION_CHOICES) + 1, + max_height=2, + max_width=80, scroll_exit=True, ) self.max_cache_size = self.add_widget_intelligent( @@ -370,12 +386,6 @@ Use cursor arrows to make a checkbox selection, and space to toggle. scroll_exit=True, ) self.nextrely += 1 - self.add_widget_intelligent( - npyscreen.FixedText, - value="Folder to recursively scan for new checkpoints, ControlNets, LoRAs and TI models ( autocompletes, ctrl-N advances):", - editable=False, - color="CONTROL", - ) self.outdir = self.add_widget_intelligent( FileBox, name="Output directory for images ( autocompletes, ctrl-N advances):", @@ -389,33 +399,25 @@ Use cursor arrows to make a checkbox selection, and space to toggle. scroll_exit=True, ) self.autoimport_dirs = {} - self.autoimport_dirs['autoimport_dir'] = self.add_widget_intelligent( - FileBox, - name=f'Autoimport Folder', - value=str(config.root_path / config.autoimport_dir), - select_dir=True, - must_exist=False, - use_two_lines=False, - labelColor="GOOD", - begin_entry_at=32, - max_height = 3, - scroll_exit=True - ) - self.nextrely += 1 - self.add_widget_intelligent( - npyscreen.TitleFixedText, - name="== LICENSE ==", - begin_entry_at=0, - editable=False, - color="CONTROL", + self.autoimport_dirs["autoimport_dir"] = self.add_widget_intelligent( + FileBox, + name=f"Folder to recursively scan for new checkpoints, ControlNets, LoRAs and TI models", + value=str(config.root_path / config.autoimport_dir), + select_dir=True, + must_exist=False, + use_two_lines=False, + labelColor="GOOD", + begin_entry_at=32, + max_height=3, scroll_exit=True, ) - self.nextrely -= 1 + self.nextrely += 1 label = """BY DOWNLOADING THE STABLE DIFFUSION WEIGHT FILES, YOU AGREE TO HAVE READ -AND ACCEPTED THE CREATIVEML RESPONSIBLE AI LICENSE LOCATED AT -https://huggingface.co/spaces/CompVis/stable-diffusion-license +AND ACCEPTED THE CREATIVEML RESPONSIBLE AI LICENSES LOCATED AT +https://huggingface.co/spaces/CompVis/stable-diffusion-license and +https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/LICENSE.md """ - for i in textwrap.wrap(label,width=window_width-6): + for i in textwrap.wrap(label, width=window_width - 6): self.add_widget_intelligent( npyscreen.FixedText, value=i, @@ -424,22 +426,17 @@ https://huggingface.co/spaces/CompVis/stable-diffusion-license ) self.license_acceptance = self.add_widget_intelligent( npyscreen.Checkbox, - name="I accept the CreativeML Responsible AI License", + name="I accept the CreativeML Responsible AI Licenses", value=not first_time, relx=2, scroll_exit=True, ) self.nextrely += 1 - label = ( - "DONE" - if program_opts.skip_sd_weights or program_opts.default_only - else "NEXT" - ) + label = "DONE" if program_opts.skip_sd_weights or program_opts.default_only else "NEXT" self.ok_button = self.add_widget_intelligent( CenteredButtonPress, name=label, relx=(window_width - len(label)) // 2, - rely=-3, when_pressed_function=self.on_ok, ) @@ -454,13 +451,11 @@ https://huggingface.co/spaces/CompVis/stable-diffusion-license self.editing = False else: self.editing = True - + def validate_field_values(self, opt: Namespace) -> bool: bad_fields = [] if not opt.license_acceptance: - bad_fields.append( - "Please accept the license terms before proceeding to model downloads" - ) + bad_fields.append("Please accept the license terms before proceeding to model downloads") if not Path(opt.outdir).parent.exists(): bad_fields.append( f"The output directory does not seem to be valid. Please check that {str(Path(opt.outdir).parent)} is an existing directory." @@ -478,11 +473,11 @@ https://huggingface.co/spaces/CompVis/stable-diffusion-license new_opts = Namespace() for attr in [ - "outdir", - "free_gpu_mem", - "max_cache_size", - "xformers_enabled", - "always_use_cpu", + "outdir", + "free_gpu_mem", + "max_cache_size", + "xformers_enabled", + "always_use_cpu", ]: setattr(new_opts, attr, getattr(self, attr).value) @@ -495,7 +490,7 @@ https://huggingface.co/spaces/CompVis/stable-diffusion-license new_opts.hf_token = self.hf_token.value new_opts.license_acceptance = self.license_acceptance.value new_opts.precision = PRECISION_CHOICES[self.precision.value[0]] - + return new_opts @@ -534,19 +529,20 @@ def edit_opts(program_opts: Namespace, invokeai_opts: Namespace) -> argparse.Nam editApp.run() return editApp.new_opts() + def default_startup_options(init_file: Path) -> Namespace: opts = InvokeAIAppConfig.get_config() return opts + def default_user_selections(program_opts: Namespace) -> InstallSelections: - try: installer = ModelInstall(config) except omegaconf.errors.ConfigKeyError: - logger.warning('Your models.yaml file is corrupt or out of date. Reinitializing') + logger.warning("Your models.yaml file is corrupt or out of date. Reinitializing") initialize_rootdir(config.root_path, True) installer = ModelInstall(config) - + models = installer.all_models() return InstallSelections( install_models=[models[installer.default_model()].path or models[installer.default_model()].repo_id] @@ -556,44 +552,46 @@ def default_user_selections(program_opts: Namespace) -> InstallSelections: else list(), ) + # ------------------------------------- def initialize_rootdir(root: Path, yes_to_all: bool = False): logger.info("Initializing InvokeAI runtime directory") - for name in ( - "models", - "databases", - "text-inversion-output", - "text-inversion-training-data", - "configs" - ): + for name in ("models", "databases", "text-inversion-output", "text-inversion-training-data", "configs"): os.makedirs(os.path.join(root, name), exist_ok=True) for model_type in ModelType: - Path(root, 'autoimport', model_type.value).mkdir(parents=True, exist_ok=True) + Path(root, "autoimport", model_type.value).mkdir(parents=True, exist_ok=True) configs_src = Path(configs.__path__[0]) configs_dest = root / "configs" if not os.path.samefile(configs_src, configs_dest): shutil.copytree(configs_src, configs_dest, dirs_exist_ok=True) - dest = root / 'models' + dest = root / "models" for model_base in BaseModelType: for model_type in ModelType: path = dest / model_base.value / model_type.value path.mkdir(parents=True, exist_ok=True) - path = dest / 'core' + path = dest / "core" path.mkdir(parents=True, exist_ok=True) - with open(root / 'configs' / 'models.yaml','w') as yaml_file: - yaml_file.write(yaml.dump({'__metadata__': - {'version':'3.0.0'} - } - ) - ) - + maybe_create_models_yaml(root) + + +def maybe_create_models_yaml(root: Path): + models_yaml = root / "configs" / "models.yaml" + if models_yaml.exists(): + if OmegaConf.load(models_yaml).get("__metadata__"): # up to date + return + else: + logger.info("Creating new models.yaml, original saved as models.yaml.orig") + models_yaml.rename(models_yaml.parent / "models.yaml.orig") + + with open(models_yaml, "w") as yaml_file: + yaml_file.write(yaml.dump({"__metadata__": {"version": "3.0.0"}})) + + # ------------------------------------- -def run_console_ui( - program_opts: Namespace, initfile: Path = None -) -> (Namespace, Namespace): +def run_console_ui(program_opts: Namespace, initfile: Path = None) -> (Namespace, Namespace): # parse_args() will read from init file if present invokeai_opts = default_startup_options(initfile) invokeai_opts.root = program_opts.root @@ -605,8 +603,9 @@ def run_console_ui( # the install-models application spawns a subprocess to install # models, and will crash unless this is set before running. import torch + torch.multiprocessing.set_start_method("spawn") - + editApp = EditOptApplication(program_opts, invokeai_opts) editApp.run() if editApp.user_cancelled: @@ -623,39 +622,42 @@ def write_opts(opts: Namespace, init_file: Path): # this will load current settings new_config = InvokeAIAppConfig.get_config() new_config.root = config.root - - for key,value in opts.__dict__.items(): - if hasattr(new_config,key): - setattr(new_config,key,value) - with open(init_file,'w', encoding='utf-8') as file: + for key, value in opts.__dict__.items(): + if hasattr(new_config, key): + setattr(new_config, key, value) + + with open(init_file, "w", encoding="utf-8") as file: file.write(new_config.to_yaml()) - if hasattr(opts,'hf_token') and opts.hf_token: + if hasattr(opts, "hf_token") and opts.hf_token: HfLogin(opts.hf_token) + # ------------------------------------- def default_output_dir() -> Path: return config.root_path / "outputs" + # ------------------------------------- def write_default_options(program_opts: Namespace, initfile: Path): opt = default_startup_options(initfile) write_opts(opt, initfile) + # ------------------------------------- # Here we bring in # the legacy Args object in order to parse # the old init file and write out the new # yaml format. -def migrate_init_file(legacy_format:Path): - old = legacy_parser.parse_args([f'@{str(legacy_format)}']) +def migrate_init_file(legacy_format: Path): + old = legacy_parser.parse_args([f"@{str(legacy_format)}"]) new = InvokeAIAppConfig.get_config() fields = list(get_type_hints(InvokeAIAppConfig).keys()) for attr in fields: - if hasattr(old,attr): - setattr(new,attr,getattr(old,attr)) + if hasattr(old, attr): + setattr(new, attr, getattr(old, attr)) # a few places where the field names have changed and we have to # manually add in the new names/values @@ -663,40 +665,43 @@ def migrate_init_file(legacy_format:Path): new.conf_path = old.conf new.root = legacy_format.parent.resolve() - invokeai_yaml = legacy_format.parent / 'invokeai.yaml' - with open(invokeai_yaml,"w", encoding="utf-8") as outfile: + invokeai_yaml = legacy_format.parent / "invokeai.yaml" + with open(invokeai_yaml, "w", encoding="utf-8") as outfile: outfile.write(new.to_yaml()) - legacy_format.replace(legacy_format.parent / 'invokeai.init.orig') + legacy_format.replace(legacy_format.parent / "invokeai.init.orig") + # ------------------------------------- def migrate_models(root: Path): from invokeai.backend.install.migrate_to_3 import do_migrate + do_migrate(root, root) -def migrate_if_needed(opt: Namespace, root: Path)->bool: - # We check for to see if the runtime directory is correctly initialized. - old_init_file = root / 'invokeai.init' - new_init_file = root / 'invokeai.yaml' - old_hub = root / 'models/hub' - migration_needed = (old_init_file.exists() and not new_init_file.exists()) and old_hub.exists() - - if migration_needed: - if opt.yes_to_all or \ - yes_or_no(f'{str(config.root_path)} appears to be a 2.3 format root directory. Convert to version 3.0?'): - logger.info('** Migrating invokeai.init to invokeai.yaml') +def migrate_if_needed(opt: Namespace, root: Path) -> bool: + # We check for to see if the runtime directory is correctly initialized. + old_init_file = root / "invokeai.init" + new_init_file = root / "invokeai.yaml" + old_hub = root / "models/hub" + migration_needed = (old_init_file.exists() and not new_init_file.exists()) and old_hub.exists() + + if migration_needed: + if opt.yes_to_all or yes_or_no( + f"{str(config.root_path)} appears to be a 2.3 format root directory. Convert to version 3.0?" + ): + logger.info("** Migrating invokeai.init to invokeai.yaml") migrate_init_file(old_init_file) - config.parse_args(argv=[],conf=OmegaConf.load(new_init_file)) + config.parse_args(argv=[], conf=OmegaConf.load(new_init_file)) if old_hub.exists(): migrate_models(config.root_path) else: - print('Cannot continue without conversion. Aborting.') - + print("Cannot continue without conversion. Aborting.") + return migration_needed - + # ------------------------------------- def main(): parser = argparse.ArgumentParser(description="InvokeAI model downloader") @@ -753,9 +758,9 @@ def main(): invoke_args = [] if opt.root: - invoke_args.extend(['--root',opt.root]) + invoke_args.extend(["--root", opt.root]) if opt.full_precision: - invoke_args.extend(['--precision','float32']) + invoke_args.extend(["--precision", "float32"]) config.parse_args(invoke_args) logger = InvokeAILogger().getLogger(config=config) @@ -771,22 +776,18 @@ def main(): initialize_rootdir(config.root_path, opt.yes_to_all) models_to_download = default_user_selections(opt) - new_init_file = config.root_path / 'invokeai.yaml' + new_init_file = config.root_path / "invokeai.yaml" if opt.yes_to_all: write_default_options(opt, new_init_file) - init_options = Namespace( - precision="float32" if opt.full_precision else "float16" - ) + init_options = Namespace(precision="float32" if opt.full_precision else "float16") else: init_options, models_to_download = run_console_ui(opt, new_init_file) if init_options: write_opts(init_options, new_init_file) else: - logger.info( - '\n** CANCELLED AT USER\'S REQUEST. USE THE "invoke.sh" LAUNCHER TO RUN LATER **\n' - ) + logger.info('\n** CANCELLED AT USER\'S REQUEST. USE THE "invoke.sh" LAUNCHER TO RUN LATER **\n') sys.exit(0) - + if opt.skip_support_models: logger.info("Skipping support models at user's request") else: @@ -800,7 +801,7 @@ def main(): postscript(errors=errors) if not opt.yes_to_all: - input('Press any key to continue...') + input("Press any key to continue...") except KeyboardInterrupt: print("\nGoodbye! Come back soon.") diff --git a/invokeai/backend/install/legacy_arg_parsing.py b/invokeai/backend/install/legacy_arg_parsing.py index 684c50c77d..f6a0682f2a 100644 --- a/invokeai/backend/install/legacy_arg_parsing.py +++ b/invokeai/backend/install/legacy_arg_parsing.py @@ -47,17 +47,18 @@ PRECISION_CHOICES = [ "float16", ] + class FileArgumentParser(ArgumentParser): """ Supports reading defaults from an init file. """ + def convert_arg_line_to_args(self, arg_line): return shlex.split(arg_line, comments=True) legacy_parser = FileArgumentParser( - description= - """ + description=""" Generate images using Stable Diffusion. Use --web to launch the web interface. Use --from_file to load prompts from a file path or standard input ("-"). @@ -65,304 +66,279 @@ Generate images using Stable Diffusion. Other command-line arguments are defaults that can usually be overridden prompt the command prompt. """, - fromfile_prefix_chars='@', + fromfile_prefix_chars="@", ) -general_group = legacy_parser.add_argument_group('General') -model_group = legacy_parser.add_argument_group('Model selection') -file_group = legacy_parser.add_argument_group('Input/output') -web_server_group = legacy_parser.add_argument_group('Web server') -render_group = legacy_parser.add_argument_group('Rendering') -postprocessing_group = legacy_parser.add_argument_group('Postprocessing') -deprecated_group = legacy_parser.add_argument_group('Deprecated options') +general_group = legacy_parser.add_argument_group("General") +model_group = legacy_parser.add_argument_group("Model selection") +file_group = legacy_parser.add_argument_group("Input/output") +web_server_group = legacy_parser.add_argument_group("Web server") +render_group = legacy_parser.add_argument_group("Rendering") +postprocessing_group = legacy_parser.add_argument_group("Postprocessing") +deprecated_group = legacy_parser.add_argument_group("Deprecated options") -deprecated_group.add_argument('--laion400m') -deprecated_group.add_argument('--weights') # deprecated -general_group.add_argument( - '--version','-V', - action='store_true', - help='Print InvokeAI version number' -) +deprecated_group.add_argument("--laion400m") +deprecated_group.add_argument("--weights") # deprecated +general_group.add_argument("--version", "-V", action="store_true", help="Print InvokeAI version number") model_group.add_argument( - '--root_dir', + "--root_dir", default=None, help='Path to directory containing "models", "outputs" and "configs". If not present will read from environment variable INVOKEAI_ROOT. Defaults to ~/invokeai.', ) model_group.add_argument( - '--config', - '-c', - '-config', - dest='conf', - default='./configs/models.yaml', - help='Path to configuration file for alternate models.', + "--config", + "-c", + "-config", + dest="conf", + default="./configs/models.yaml", + help="Path to configuration file for alternate models.", ) model_group.add_argument( - '--model', + "--model", help='Indicates which diffusion model to load (defaults to "default" stanza in configs/models.yaml)', ) model_group.add_argument( - '--weight_dirs', - nargs='+', + "--weight_dirs", + nargs="+", type=str, - help='List of one or more directories that will be auto-scanned for new model weights to import', + help="List of one or more directories that will be auto-scanned for new model weights to import", ) model_group.add_argument( - '--png_compression','-z', + "--png_compression", + "-z", type=int, default=6, - choices=range(0,9), - dest='png_compression', - help='level of PNG compression, from 0 (none) to 9 (maximum). Default is 6.' + choices=range(0, 9), + dest="png_compression", + help="level of PNG compression, from 0 (none) to 9 (maximum). Default is 6.", ) model_group.add_argument( - '-F', - '--full_precision', - dest='full_precision', - action='store_true', - help='Deprecated way to set --precision=float32', + "-F", + "--full_precision", + dest="full_precision", + action="store_true", + help="Deprecated way to set --precision=float32", ) model_group.add_argument( - '--max_loaded_models', - dest='max_loaded_models', + "--max_loaded_models", + dest="max_loaded_models", type=int, default=2, - help='Maximum number of models to keep in memory for fast switching, including the one in GPU', + help="Maximum number of models to keep in memory for fast switching, including the one in GPU", ) model_group.add_argument( - '--free_gpu_mem', - dest='free_gpu_mem', - action='store_true', - help='Force free gpu memory before final decoding', + "--free_gpu_mem", + dest="free_gpu_mem", + action="store_true", + help="Force free gpu memory before final decoding", ) model_group.add_argument( - '--sequential_guidance', - dest='sequential_guidance', - action='store_true', - help="Calculate guidance in serial instead of in parallel, lowering memory requirement " - "at the expense of speed", + "--sequential_guidance", + dest="sequential_guidance", + action="store_true", + help="Calculate guidance in serial instead of in parallel, lowering memory requirement " "at the expense of speed", ) model_group.add_argument( - '--xformers', + "--xformers", action=argparse.BooleanOptionalAction, default=True, - help='Enable/disable xformers support (default enabled if installed)', + help="Enable/disable xformers support (default enabled if installed)", ) model_group.add_argument( - "--always_use_cpu", - dest="always_use_cpu", - action="store_true", - help="Force use of CPU even if GPU is available" + "--always_use_cpu", dest="always_use_cpu", action="store_true", help="Force use of CPU even if GPU is available" ) model_group.add_argument( - '--precision', - dest='precision', + "--precision", + dest="precision", type=str, choices=PRECISION_CHOICES, - metavar='PRECISION', + metavar="PRECISION", help=f'Set model precision. Defaults to auto selected based on device. Options: {", ".join(PRECISION_CHOICES)}', - default='auto', + default="auto", ) model_group.add_argument( - '--ckpt_convert', + "--ckpt_convert", action=argparse.BooleanOptionalAction, - dest='ckpt_convert', + dest="ckpt_convert", default=True, - help='Deprecated option. Legacy ckpt files are now always converted to diffusers when loaded.' + help="Deprecated option. Legacy ckpt files are now always converted to diffusers when loaded.", ) model_group.add_argument( - '--internet', + "--internet", action=argparse.BooleanOptionalAction, - dest='internet_available', + dest="internet_available", default=True, - help='Indicate whether internet is available for just-in-time model downloading (default: probe automatically).', + help="Indicate whether internet is available for just-in-time model downloading (default: probe automatically).", ) model_group.add_argument( - '--nsfw_checker', - '--safety_checker', + "--nsfw_checker", + "--safety_checker", action=argparse.BooleanOptionalAction, - dest='safety_checker', + dest="safety_checker", default=False, - help='Check for and blur potentially NSFW images. Use --no-nsfw_checker to disable.', + help="Check for and blur potentially NSFW images. Use --no-nsfw_checker to disable.", ) model_group.add_argument( - '--autoimport', + "--autoimport", default=None, type=str, - help='Check the indicated directory for .ckpt/.safetensors weights files at startup and import directly', + help="Check the indicated directory for .ckpt/.safetensors weights files at startup and import directly", ) model_group.add_argument( - '--autoconvert', + "--autoconvert", default=None, type=str, - help='Check the indicated directory for .ckpt/.safetensors weights files at startup and import as optimized diffuser models', + help="Check the indicated directory for .ckpt/.safetensors weights files at startup and import as optimized diffuser models", ) model_group.add_argument( - '--patchmatch', + "--patchmatch", action=argparse.BooleanOptionalAction, default=True, - help='Load the patchmatch extension for outpainting. Use --no-patchmatch to disable.', + help="Load the patchmatch extension for outpainting. Use --no-patchmatch to disable.", ) file_group.add_argument( - '--from_file', - dest='infile', + "--from_file", + dest="infile", type=str, - help='If specified, load prompts from this file', + help="If specified, load prompts from this file", ) file_group.add_argument( - '--outdir', - '-o', + "--outdir", + "-o", type=str, - help='Directory to save generated images and a log of prompts and seeds. Default: ROOTDIR/outputs', - default='outputs', + help="Directory to save generated images and a log of prompts and seeds. Default: ROOTDIR/outputs", + default="outputs", ) file_group.add_argument( - '--prompt_as_dir', - '-p', - action='store_true', - help='Place images in subdirectories named after the prompt.', + "--prompt_as_dir", + "-p", + action="store_true", + help="Place images in subdirectories named after the prompt.", ) render_group.add_argument( - '--fnformat', - default='{prefix}.{seed}.png', + "--fnformat", + default="{prefix}.{seed}.png", type=str, - help='Overwrite the filename format. You can use any argument as wildcard enclosed in curly braces. Default is {prefix}.{seed}.png', + help="Overwrite the filename format. You can use any argument as wildcard enclosed in curly braces. Default is {prefix}.{seed}.png", ) +render_group.add_argument("-s", "--steps", type=int, default=50, help="Number of steps") render_group.add_argument( - '-s', - '--steps', + "-W", + "--width", type=int, - default=50, - help='Number of steps' + help="Image width, multiple of 64", ) render_group.add_argument( - '-W', - '--width', + "-H", + "--height", type=int, - help='Image width, multiple of 64', + help="Image height, multiple of 64", ) render_group.add_argument( - '-H', - '--height', - type=int, - help='Image height, multiple of 64', -) -render_group.add_argument( - '-C', - '--cfg_scale', + "-C", + "--cfg_scale", default=7.5, type=float, help='Classifier free guidance (CFG) scale - higher numbers cause generator to "try" harder.', ) render_group.add_argument( - '--sampler', - '-A', - '-m', - dest='sampler_name', + "--sampler", + "-A", + "-m", + dest="sampler_name", type=str, choices=SAMPLER_CHOICES, - metavar='SAMPLER_NAME', + metavar="SAMPLER_NAME", help=f'Set the default sampler. Supported samplers: {", ".join(SAMPLER_CHOICES)}', - default='k_lms', + default="k_lms", ) render_group.add_argument( - '--log_tokenization', - '-t', - action='store_true', - help='shows how the prompt is split into tokens' + "--log_tokenization", "-t", action="store_true", help="shows how the prompt is split into tokens" ) render_group.add_argument( - '-f', - '--strength', + "-f", + "--strength", type=float, - help='img2img strength for noising/unnoising. 0.0 preserves image exactly, 1.0 replaces it completely', + help="img2img strength for noising/unnoising. 0.0 preserves image exactly, 1.0 replaces it completely", ) render_group.add_argument( - '-T', - '-fit', - '--fit', + "-T", + "-fit", + "--fit", action=argparse.BooleanOptionalAction, - help='If specified, will resize the input image to fit within the dimensions of width x height (512x512 default)', + help="If specified, will resize the input image to fit within the dimensions of width x height (512x512 default)", ) +render_group.add_argument("--grid", "-g", action=argparse.BooleanOptionalAction, help="generate a grid") render_group.add_argument( - '--grid', - '-g', - action=argparse.BooleanOptionalAction, - help='generate a grid' -) -render_group.add_argument( - '--embedding_directory', - '--embedding_path', - dest='embedding_path', - default='embeddings', + "--embedding_directory", + "--embedding_path", + dest="embedding_path", + default="embeddings", type=str, - help='Path to a directory containing .bin and/or .pt files, or a single .bin/.pt file. You may use subdirectories. (default is ROOTDIR/embeddings)' + help="Path to a directory containing .bin and/or .pt files, or a single .bin/.pt file. You may use subdirectories. (default is ROOTDIR/embeddings)", ) render_group.add_argument( - '--lora_directory', - dest='lora_path', - default='loras', + "--lora_directory", + dest="lora_path", + default="loras", type=str, - help='Path to a directory containing LoRA files; subdirectories are not supported. (default is ROOTDIR/loras)' + help="Path to a directory containing LoRA files; subdirectories are not supported. (default is ROOTDIR/loras)", ) render_group.add_argument( - '--embeddings', + "--embeddings", action=argparse.BooleanOptionalAction, default=True, - help='Enable embedding directory (default). Use --no-embeddings to disable.', + help="Enable embedding directory (default). Use --no-embeddings to disable.", ) +render_group.add_argument("--enable_image_debugging", action="store_true", help="Generates debugging image to display") render_group.add_argument( - '--enable_image_debugging', - action='store_true', - help='Generates debugging image to display' -) -render_group.add_argument( - '--karras_max', + "--karras_max", type=int, default=None, - help="control the point at which the K* samplers will shift from using the Karras noise schedule (good for low step counts) to the LatentDiffusion noise schedule (good for high step counts). Set to 0 to use LatentDiffusion for all step values, and to a high value (e.g. 1000) to use Karras for all step values. [29]." + help="control the point at which the K* samplers will shift from using the Karras noise schedule (good for low step counts) to the LatentDiffusion noise schedule (good for high step counts). Set to 0 to use LatentDiffusion for all step values, and to a high value (e.g. 1000) to use Karras for all step values. [29].", ) # Restoration related args postprocessing_group.add_argument( - '--no_restore', - dest='restore', - action='store_false', - help='Disable face restoration with GFPGAN or codeformer', + "--no_restore", + dest="restore", + action="store_false", + help="Disable face restoration with GFPGAN or codeformer", ) postprocessing_group.add_argument( - '--no_upscale', - dest='esrgan', - action='store_false', - help='Disable upscaling with ESRGAN', + "--no_upscale", + dest="esrgan", + action="store_false", + help="Disable upscaling with ESRGAN", ) postprocessing_group.add_argument( - '--esrgan_bg_tile', + "--esrgan_bg_tile", type=int, default=400, - help='Tile size for background sampler, 0 for no tile during testing. Default: 400.', + help="Tile size for background sampler, 0 for no tile during testing. Default: 400.", ) postprocessing_group.add_argument( - '--esrgan_denoise_str', + "--esrgan_denoise_str", type=float, default=0.75, - help='esrgan denoise str. 0 is no denoise, 1 is max denoise. Default: 0.75', + help="esrgan denoise str. 0 is no denoise, 1 is max denoise. Default: 0.75", ) postprocessing_group.add_argument( - '--gfpgan_model_path', + "--gfpgan_model_path", type=str, - default='./models/gfpgan/GFPGANv1.4.pth', - help='Indicates the path to the GFPGAN model', + default="./models/gfpgan/GFPGANv1.4.pth", + help="Indicates the path to the GFPGAN model", ) web_server_group.add_argument( - '--web', - dest='web', - action='store_true', - help='Start in web server mode.', + "--web", + dest="web", + action="store_true", + help="Start in web server mode.", ) web_server_group.add_argument( - '--web_develop', - dest='web_develop', - action='store_true', - help='Start in web server development mode.', + "--web_develop", + dest="web_develop", + action="store_true", + help="Start in web server development mode.", ) web_server_group.add_argument( "--web_verbose", @@ -376,32 +352,27 @@ web_server_group.add_argument( help="Additional allowed origins, comma-separated", ) web_server_group.add_argument( - '--host', + "--host", type=str, - default='127.0.0.1', - help='Web server: Host or IP to listen on. Set to 0.0.0.0 to accept traffic from other devices on your network.' + default="127.0.0.1", + help="Web server: Host or IP to listen on. Set to 0.0.0.0 to accept traffic from other devices on your network.", ) +web_server_group.add_argument("--port", type=int, default="9090", help="Web server: Port to listen on") web_server_group.add_argument( - '--port', - type=int, - default='9090', - help='Web server: Port to listen on' -) -web_server_group.add_argument( - '--certfile', + "--certfile", type=str, default=None, - help='Web server: Path to certificate file to use for SSL. Use together with --keyfile' + help="Web server: Path to certificate file to use for SSL. Use together with --keyfile", ) web_server_group.add_argument( - '--keyfile', + "--keyfile", type=str, default=None, - help='Web server: Path to private key file to use for SSL. Use together with --certfile' + help="Web server: Path to private key file to use for SSL. Use together with --certfile", ) web_server_group.add_argument( - '--gui', - dest='gui', - action='store_true', - help='Start InvokeAI GUI', + "--gui", + dest="gui", + action="store_true", + help="Start InvokeAI GUI", ) diff --git a/invokeai/backend/install/migrate_to_3.py b/invokeai/backend/install/migrate_to_3.py index 85de3f5e69..9152e46951 100644 --- a/invokeai/backend/install/migrate_to_3.py +++ b/invokeai/backend/install/migrate_to_3.py @@ -1,7 +1,7 @@ -''' +""" Migrate the models directory and models.yaml file from an existing InvokeAI 2.3 installation to 3.0.0. -''' +""" import os import argparse @@ -29,14 +29,13 @@ from transformers import ( import invokeai.backend.util.logging as logger from invokeai.app.services.config import InvokeAIAppConfig from invokeai.backend.model_management import ModelManager -from invokeai.backend.model_management.model_probe import ( - ModelProbe, ModelType, BaseModelType, ModelProbeInfo - ) +from invokeai.backend.model_management.model_probe import ModelProbe, ModelType, BaseModelType, ModelProbeInfo warnings.filterwarnings("ignore") transformers.logging.set_verbosity_error() diffusers.logging.set_verbosity_error() + # holder for paths that we will migrate @dataclass class ModelPaths: @@ -45,81 +44,82 @@ class ModelPaths: loras: Path controlnets: Path + class MigrateTo3(object): - def __init__(self, - from_root: Path, - to_models: Path, - model_manager: ModelManager, - src_paths: ModelPaths, - ): + def __init__( + self, + from_root: Path, + to_models: Path, + model_manager: ModelManager, + src_paths: ModelPaths, + ): self.root_directory = from_root self.dest_models = to_models self.mgr = model_manager self.src_paths = src_paths - + @classmethod def initialize_yaml(cls, yaml_file: Path): - with open(yaml_file, 'w') as file: - file.write( - yaml.dump( - { - '__metadata__': {'version':'3.0.0'} - } - ) - ) - + with open(yaml_file, "w") as file: + file.write(yaml.dump({"__metadata__": {"version": "3.0.0"}})) + def create_directory_structure(self): - ''' + """ Create the basic directory structure for the models folder. - ''' - for model_base in [BaseModelType.StableDiffusion1,BaseModelType.StableDiffusion2]: - for model_type in [ModelType.Main, ModelType.Vae, ModelType.Lora, - ModelType.ControlNet,ModelType.TextualInversion]: + """ + for model_base in [BaseModelType.StableDiffusion1, BaseModelType.StableDiffusion2]: + for model_type in [ + ModelType.Main, + ModelType.Vae, + ModelType.Lora, + ModelType.ControlNet, + ModelType.TextualInversion, + ]: path = self.dest_models / model_base.value / model_type.value path.mkdir(parents=True, exist_ok=True) - path = self.dest_models / 'core' + path = self.dest_models / "core" path.mkdir(parents=True, exist_ok=True) @staticmethod - def copy_file(src:Path,dest:Path): - ''' + def copy_file(src: Path, dest: Path): + """ copy a single file with logging - ''' + """ if dest.exists(): - logger.info(f'Skipping existing {str(dest)}') + logger.info(f"Skipping existing {str(dest)}") return - logger.info(f'Copying {str(src)} to {str(dest)}') + logger.info(f"Copying {str(src)} to {str(dest)}") try: shutil.copy(src, dest) except Exception as e: - logger.error(f'COPY FAILED: {str(e)}') + logger.error(f"COPY FAILED: {str(e)}") @staticmethod - def copy_dir(src:Path,dest:Path): - ''' + def copy_dir(src: Path, dest: Path): + """ Recursively copy a directory with logging - ''' + """ if dest.exists(): - logger.info(f'Skipping existing {str(dest)}') + logger.info(f"Skipping existing {str(dest)}") return - - logger.info(f'Copying {str(src)} to {str(dest)}') + + logger.info(f"Copying {str(src)} to {str(dest)}") try: shutil.copytree(src, dest) except Exception as e: - logger.error(f'COPY FAILED: {str(e)}') + logger.error(f"COPY FAILED: {str(e)}") def migrate_models(self, src_dir: Path): - ''' + """ Recursively walk through src directory, probe anything that looks like a model, and copy the model into the appropriate location within the destination models directory. - ''' + """ directories_scanned = set() for root, dirs, files in os.walk(src_dir): for d in dirs: try: - model = Path(root,d) + model = Path(root, d) info = ModelProbe().heuristic_probe(model) if not info: continue @@ -136,9 +136,9 @@ class MigrateTo3(object): # don't copy raw learned_embeds.bin or pytorch_lora_weights.bin # let them be copied as part of a tree copy operation try: - if f in {'learned_embeds.bin','pytorch_lora_weights.bin'}: + if f in {"learned_embeds.bin", "pytorch_lora_weights.bin"}: continue - model = Path(root,f) + model = Path(root, f) if model.parent in directories_scanned: continue info = ModelProbe().heuristic_probe(model) @@ -154,148 +154,146 @@ class MigrateTo3(object): logger.error(str(e)) def migrate_support_models(self): - ''' + """ Copy the clipseg, upscaler, and restoration models to their new locations. - ''' + """ dest_directory = self.dest_models - if (self.root_directory / 'models/clipseg').exists(): - self.copy_dir(self.root_directory / 'models/clipseg', dest_directory / 'core/misc/clipseg') - if (self.root_directory / 'models/realesrgan').exists(): - self.copy_dir(self.root_directory / 'models/realesrgan', dest_directory / 'core/upscaling/realesrgan') - for d in ['codeformer','gfpgan']: - path = self.root_directory / 'models' / d + if (self.root_directory / "models/clipseg").exists(): + self.copy_dir(self.root_directory / "models/clipseg", dest_directory / "core/misc/clipseg") + if (self.root_directory / "models/realesrgan").exists(): + self.copy_dir(self.root_directory / "models/realesrgan", dest_directory / "core/upscaling/realesrgan") + for d in ["codeformer", "gfpgan"]: + path = self.root_directory / "models" / d if path.exists(): - self.copy_dir(path,dest_directory / f'core/face_restoration/{d}') + self.copy_dir(path, dest_directory / f"core/face_restoration/{d}") def migrate_tuning_models(self): - ''' + """ Migrate the embeddings, loras and controlnets directories to their new homes. - ''' + """ for src in [self.src_paths.embeddings, self.src_paths.loras, self.src_paths.controlnets]: if not src: continue if src.is_dir(): - logger.info(f'Scanning {src}') + logger.info(f"Scanning {src}") self.migrate_models(src) else: - logger.info(f'{src} directory not found; skipping') + logger.info(f"{src} directory not found; skipping") continue def migrate_conversion_models(self): - ''' + """ Migrate all the models that are needed by the ckpt_to_diffusers conversion script. - ''' + """ dest_directory = self.dest_models kwargs = dict( - cache_dir = self.root_directory / 'models/hub', - #local_files_only = True + cache_dir=self.root_directory / "models/hub", + # local_files_only = True ) try: - logger.info('Migrating core tokenizers and text encoders') - target_dir = dest_directory / 'core' / 'convert' + logger.info("Migrating core tokenizers and text encoders") + target_dir = dest_directory / "core" / "convert" - self._migrate_pretrained(BertTokenizerFast, - repo_id='bert-base-uncased', - dest = target_dir / 'bert-base-uncased', - **kwargs) + self._migrate_pretrained( + BertTokenizerFast, repo_id="bert-base-uncased", dest=target_dir / "bert-base-uncased", **kwargs + ) # sd-1 - repo_id = 'openai/clip-vit-large-patch14' - self._migrate_pretrained(CLIPTokenizer, - repo_id= repo_id, - dest= target_dir / 'clip-vit-large-patch14', - **kwargs) - self._migrate_pretrained(CLIPTextModel, - repo_id = repo_id, - dest = target_dir / 'clip-vit-large-patch14', - force = True, - **kwargs) + repo_id = "openai/clip-vit-large-patch14" + self._migrate_pretrained( + CLIPTokenizer, repo_id=repo_id, dest=target_dir / "clip-vit-large-patch14", **kwargs + ) + self._migrate_pretrained( + CLIPTextModel, repo_id=repo_id, dest=target_dir / "clip-vit-large-patch14", force=True, **kwargs + ) # sd-2 repo_id = "stabilityai/stable-diffusion-2" - self._migrate_pretrained(CLIPTokenizer, - repo_id = repo_id, - dest = target_dir / 'stable-diffusion-2-clip' / 'tokenizer', - **{'subfolder':'tokenizer',**kwargs} - ) - self._migrate_pretrained(CLIPTextModel, - repo_id = repo_id, - dest = target_dir / 'stable-diffusion-2-clip' / 'text_encoder', - **{'subfolder':'text_encoder',**kwargs} - ) + self._migrate_pretrained( + CLIPTokenizer, + repo_id=repo_id, + dest=target_dir / "stable-diffusion-2-clip" / "tokenizer", + **{"subfolder": "tokenizer", **kwargs}, + ) + self._migrate_pretrained( + CLIPTextModel, + repo_id=repo_id, + dest=target_dir / "stable-diffusion-2-clip" / "text_encoder", + **{"subfolder": "text_encoder", **kwargs}, + ) # VAE - logger.info('Migrating stable diffusion VAE') - self._migrate_pretrained(AutoencoderKL, - repo_id = 'stabilityai/sd-vae-ft-mse', - dest = target_dir / 'sd-vae-ft-mse', - **kwargs) - + logger.info("Migrating stable diffusion VAE") + self._migrate_pretrained( + AutoencoderKL, repo_id="stabilityai/sd-vae-ft-mse", dest=target_dir / "sd-vae-ft-mse", **kwargs + ) + # safety checking - logger.info('Migrating safety checker') + logger.info("Migrating safety checker") repo_id = "CompVis/stable-diffusion-safety-checker" - self._migrate_pretrained(AutoFeatureExtractor, - repo_id = repo_id, - dest = target_dir / 'stable-diffusion-safety-checker', - **kwargs) - self._migrate_pretrained(StableDiffusionSafetyChecker, - repo_id = repo_id, - dest = target_dir / 'stable-diffusion-safety-checker', - **kwargs) + self._migrate_pretrained( + AutoFeatureExtractor, repo_id=repo_id, dest=target_dir / "stable-diffusion-safety-checker", **kwargs + ) + self._migrate_pretrained( + StableDiffusionSafetyChecker, + repo_id=repo_id, + dest=target_dir / "stable-diffusion-safety-checker", + **kwargs, + ) except KeyboardInterrupt: raise except Exception as e: logger.error(str(e)) - def _model_probe_to_path(self, info: ModelProbeInfo)->Path: + def _model_probe_to_path(self, info: ModelProbeInfo) -> Path: return Path(self.dest_models, info.base_type.value, info.model_type.value) - def _migrate_pretrained(self, model_class, repo_id: str, dest: Path, force:bool=False, **kwargs): + def _migrate_pretrained(self, model_class, repo_id: str, dest: Path, force: bool = False, **kwargs): if dest.exists() and not force: - logger.info(f'Skipping existing {dest}') + logger.info(f"Skipping existing {dest}") return model = model_class.from_pretrained(repo_id, **kwargs) self._save_pretrained(model, dest, overwrite=force) - def _save_pretrained(self, model, dest: Path, overwrite: bool=False): + def _save_pretrained(self, model, dest: Path, overwrite: bool = False): model_name = dest.name if overwrite: model.save_pretrained(dest, safe_serialization=True) else: - download_path = dest.with_name(f'{model_name}.downloading') + download_path = dest.with_name(f"{model_name}.downloading") model.save_pretrained(download_path, safe_serialization=True) download_path.replace(dest) - def _download_vae(self, repo_id: str, subfolder:str=None)->Path: - vae = AutoencoderKL.from_pretrained(repo_id, cache_dir=self.root_directory / 'models/hub', subfolder=subfolder) + def _download_vae(self, repo_id: str, subfolder: str = None) -> Path: + vae = AutoencoderKL.from_pretrained(repo_id, cache_dir=self.root_directory / "models/hub", subfolder=subfolder) info = ModelProbe().heuristic_probe(vae) - _, model_name = repo_id.split('/') + _, model_name = repo_id.split("/") dest = self._model_probe_to_path(info) / self.unique_name(model_name, info) vae.save_pretrained(dest, safe_serialization=True) return dest - def _vae_path(self, vae: Union[str,dict])->Path: - ''' + def _vae_path(self, vae: Union[str, dict]) -> Path: + """ Convert 2.3 VAE stanza to a straight path. - ''' + """ vae_path = None - + # First get a path - if isinstance(vae,str): + if isinstance(vae, str): vae_path = vae - elif isinstance(vae,DictConfig): - if p := vae.get('path'): + elif isinstance(vae, DictConfig): + if p := vae.get("path"): vae_path = p - elif repo_id := vae.get('repo_id'): - if repo_id=='stabilityai/sd-vae-ft-mse': # this guy is already downloaded - vae_path = 'models/core/convert/sd-vae-ft-mse' + elif repo_id := vae.get("repo_id"): + if repo_id == "stabilityai/sd-vae-ft-mse": # this guy is already downloaded + vae_path = "models/core/convert/sd-vae-ft-mse" return vae_path else: - vae_path = self._download_vae(repo_id, vae.get('subfolder')) + vae_path = self._download_vae(repo_id, vae.get("subfolder")) assert vae_path is not None, "Couldn't find VAE for this model" @@ -307,152 +305,144 @@ class MigrateTo3(object): dest = self._model_probe_to_path(info) / vae_path.name if not dest.exists(): if vae_path.is_dir(): - self.copy_dir(vae_path,dest) + self.copy_dir(vae_path, dest) else: - self.copy_file(vae_path,dest) + self.copy_file(vae_path, dest) vae_path = dest if vae_path.is_relative_to(self.dest_models): rel_path = vae_path.relative_to(self.dest_models) - return Path('models',rel_path) + return Path("models", rel_path) else: return vae_path - def migrate_repo_id(self, repo_id: str, model_name: str=None, **extra_config): - ''' + def migrate_repo_id(self, repo_id: str, model_name: str = None, **extra_config): + """ Migrate a locally-cached diffusers pipeline identified with a repo_id - ''' + """ dest_dir = self.dest_models - - cache = self.root_directory / 'models/hub' + + cache = self.root_directory / "models/hub" kwargs = dict( - cache_dir = cache, - safety_checker = None, + cache_dir=cache, + safety_checker=None, # local_files_only = True, ) - owner,repo_name = repo_id.split('/') + owner, repo_name = repo_id.split("/") model_name = model_name or repo_name - model = cache / '--'.join(['models',owner,repo_name]) - - if len(list(model.glob('snapshots/**/model_index.json')))==0: + model = cache / "--".join(["models", owner, repo_name]) + + if len(list(model.glob("snapshots/**/model_index.json"))) == 0: return - revisions = [x.name for x in model.glob('refs/*')] + revisions = [x.name for x in model.glob("refs/*")] # if an fp16 is available we use that - revision = 'fp16' if len(revisions) > 1 and 'fp16' in revisions else revisions[0] - pipeline = StableDiffusionPipeline.from_pretrained( - repo_id, - revision=revision, - **kwargs) + revision = "fp16" if len(revisions) > 1 and "fp16" in revisions else revisions[0] + pipeline = StableDiffusionPipeline.from_pretrained(repo_id, revision=revision, **kwargs) info = ModelProbe().heuristic_probe(pipeline) if not info: return if self.mgr.model_exists(model_name, info.base_type, info.model_type): - logger.warning(f'A model named {model_name} already exists at the destination. Skipping migration.') + logger.warning(f"A model named {model_name} already exists at the destination. Skipping migration.") return dest = self._model_probe_to_path(info) / model_name self._save_pretrained(pipeline, dest) - - rel_path = Path('models',dest.relative_to(dest_dir)) + + rel_path = Path("models", dest.relative_to(dest_dir)) self._add_model(model_name, info, rel_path, **extra_config) - def migrate_path(self, location: Path, model_name: str=None, **extra_config): - ''' + def migrate_path(self, location: Path, model_name: str = None, **extra_config): + """ Migrate a model referred to using 'weights' or 'path' - ''' + """ # handle relative paths dest_dir = self.dest_models location = self.root_directory / location model_name = model_name or location.stem - + info = ModelProbe().heuristic_probe(location) if not info: return - + if self.mgr.model_exists(model_name, info.base_type, info.model_type): - logger.warning(f'A model named {model_name} already exists at the destination. Skipping migration.') + logger.warning(f"A model named {model_name} already exists at the destination. Skipping migration.") return # uh oh, weights is in the old models directory - move it into the new one if Path(location).is_relative_to(self.src_paths.models): dest = Path(dest_dir, info.base_type.value, info.model_type.value, location.name) if location.is_dir(): - self.copy_dir(location,dest) + self.copy_dir(location, dest) else: - self.copy_file(location,dest) - location = Path('models', info.base_type.value, info.model_type.value, location.name) + self.copy_file(location, dest) + location = Path("models", info.base_type.value, info.model_type.value, location.name) self._add_model(model_name, info, location, **extra_config) - def _add_model(self, - model_name: str, - info: ModelProbeInfo, - location: Path, - **extra_config): + def _add_model(self, model_name: str, info: ModelProbeInfo, location: Path, **extra_config): if info.model_type != ModelType.Main: return - - self.mgr.add_model( - model_name = model_name, - base_model = info.base_type, - model_type = info.model_type, - clobber = True, - model_attributes = { - 'path': str(location), - 'description': f'A {info.base_type.value} {info.model_type.value} model', - 'model_format': info.format, - 'variant': info.variant_type.value, - **extra_config, - } - ) - - def migrate_defined_models(self): - ''' - Migrate models defined in models.yaml - ''' - # find any models referred to in old models.yaml - conf = OmegaConf.load(self.root_directory / 'configs/models.yaml') - - for model_name, stanza in conf.items(): + self.mgr.add_model( + model_name=model_name, + base_model=info.base_type, + model_type=info.model_type, + clobber=True, + model_attributes={ + "path": str(location), + "description": f"A {info.base_type.value} {info.model_type.value} model", + "model_format": info.format, + "variant": info.variant_type.value, + **extra_config, + }, + ) + + def migrate_defined_models(self): + """ + Migrate models defined in models.yaml + """ + # find any models referred to in old models.yaml + conf = OmegaConf.load(self.root_directory / "configs/models.yaml") + + for model_name, stanza in conf.items(): try: passthru_args = {} - - if vae := stanza.get('vae'): + + if vae := stanza.get("vae"): try: - passthru_args['vae'] = str(self._vae_path(vae)) + passthru_args["vae"] = str(self._vae_path(vae)) except Exception as e: logger.warning(f'Could not find a VAE matching "{vae}" for model "{model_name}"') logger.warning(str(e)) - if config := stanza.get('config'): - passthru_args['config'] = config + if config := stanza.get("config"): + passthru_args["config"] = config - if description:= stanza.get('description'): - passthru_args['description'] = description - - if repo_id := stanza.get('repo_id'): - logger.info(f'Migrating diffusers model {model_name}') + if description := stanza.get("description"): + passthru_args["description"] = description + + if repo_id := stanza.get("repo_id"): + logger.info(f"Migrating diffusers model {model_name}") self.migrate_repo_id(repo_id, model_name, **passthru_args) - elif location := stanza.get('weights'): - logger.info(f'Migrating checkpoint model {model_name}') + elif location := stanza.get("weights"): + logger.info(f"Migrating checkpoint model {model_name}") self.migrate_path(Path(location), model_name, **passthru_args) - - elif location := stanza.get('path'): - logger.info(f'Migrating diffusers model {model_name}') + + elif location := stanza.get("path"): + logger.info(f"Migrating diffusers model {model_name}") self.migrate_path(Path(location), model_name, **passthru_args) - + except KeyboardInterrupt: raise except Exception as e: logger.error(str(e)) - + def migrate(self): self.create_directory_structure() # the configure script is doing this @@ -461,67 +451,71 @@ class MigrateTo3(object): self.migrate_tuning_models() self.migrate_defined_models() -def _parse_legacy_initfile(root: Path, initfile: Path)->ModelPaths: - ''' + +def _parse_legacy_initfile(root: Path, initfile: Path) -> ModelPaths: + """ Returns tuple of (embedding_path, lora_path, controlnet_path) - ''' - parser = argparse.ArgumentParser(fromfile_prefix_chars='@') + """ + parser = argparse.ArgumentParser(fromfile_prefix_chars="@") parser.add_argument( - '--embedding_directory', - '--embedding_path', + "--embedding_directory", + "--embedding_path", type=Path, - dest='embedding_path', - default=Path('embeddings'), + dest="embedding_path", + default=Path("embeddings"), ) parser.add_argument( - '--lora_directory', - dest='lora_path', + "--lora_directory", + dest="lora_path", type=Path, - default=Path('loras'), + default=Path("loras"), ) - opt,_ = parser.parse_known_args([f'@{str(initfile)}']) + opt, _ = parser.parse_known_args([f"@{str(initfile)}"]) return ModelPaths( - models = root / 'models', - embeddings = root / str(opt.embedding_path).strip('"'), - loras = root / str(opt.lora_path).strip('"'), - controlnets = root / 'controlnets', + models=root / "models", + embeddings=root / str(opt.embedding_path).strip('"'), + loras=root / str(opt.lora_path).strip('"'), + controlnets=root / "controlnets", ) -def _parse_legacy_yamlfile(root: Path, initfile: Path)->ModelPaths: - ''' + +def _parse_legacy_yamlfile(root: Path, initfile: Path) -> ModelPaths: + """ Returns tuple of (embedding_path, lora_path, controlnet_path) - ''' + """ # Don't use the config object because it is unforgiving of version updates # Just use omegaconf directly opt = OmegaConf.load(initfile) paths = opt.InvokeAI.Paths - models = paths.get('models_dir','models') - embeddings = paths.get('embedding_dir','embeddings') - loras = paths.get('lora_dir','loras') - controlnets = paths.get('controlnet_dir','controlnets') + models = paths.get("models_dir", "models") + embeddings = paths.get("embedding_dir", "embeddings") + loras = paths.get("lora_dir", "loras") + controlnets = paths.get("controlnet_dir", "controlnets") return ModelPaths( - models = root / models, - embeddings = root / embeddings, - loras = root /loras, - controlnets = root / controlnets, + models=root / models, + embeddings=root / embeddings, + loras=root / loras, + controlnets=root / controlnets, ) - + + def get_legacy_embeddings(root: Path) -> ModelPaths: - path = root / 'invokeai.init' + path = root / "invokeai.init" if path.exists(): return _parse_legacy_initfile(root, path) - path = root / 'invokeai.yaml' + path = root / "invokeai.yaml" if path.exists(): return _parse_legacy_yamlfile(root, path) + def do_migrate(src_directory: Path, dest_directory: Path): """ Migrate models from src to dest InvokeAI root directories """ - config_file = dest_directory / 'configs' / 'models.yaml.3' - dest_models = dest_directory / 'models.3' - - version_3 = (dest_directory / 'models' / 'core').exists() + config_file = dest_directory / "configs" / "models.yaml.3" + dest_models = dest_directory / "models.3" + + version_3 = (dest_directory / "models" / "core").exists() # Here we create the destination models.yaml file. # If we are writing into a version 3 directory and the @@ -530,80 +524,80 @@ def do_migrate(src_directory: Path, dest_directory: Path): # create a new empty one. if version_3: # write into the dest directory try: - shutil.copy(dest_directory / 'configs' / 'models.yaml', config_file) + shutil.copy(dest_directory / "configs" / "models.yaml", config_file) except: MigrateTo3.initialize_yaml(config_file) - mgr = ModelManager(config_file) # important to initialize BEFORE moving the models directory - (dest_directory / 'models').replace(dest_models) + mgr = ModelManager(config_file) # important to initialize BEFORE moving the models directory + (dest_directory / "models").replace(dest_models) else: MigrateTo3.initialize_yaml(config_file) mgr = ModelManager(config_file) - + paths = get_legacy_embeddings(src_directory) - migrator = MigrateTo3( - from_root = src_directory, - to_models = dest_models, - model_manager = mgr, - src_paths = paths - ) + migrator = MigrateTo3(from_root=src_directory, to_models=dest_models, model_manager=mgr, src_paths=paths) migrator.migrate() print("Migration successful.") if not version_3: - (dest_directory / 'models').replace(src_directory / 'models.orig') - print(f'Original models directory moved to {dest_directory}/models.orig') - - (dest_directory / 'configs' / 'models.yaml').replace(src_directory / 'configs' / 'models.yaml.orig') - print(f'Original models.yaml file moved to {dest_directory}/configs/models.yaml.orig') - - config_file.replace(config_file.with_suffix('')) - dest_models.replace(dest_models.with_suffix('')) - + (dest_directory / "models").replace(src_directory / "models.orig") + print(f"Original models directory moved to {dest_directory}/models.orig") + + (dest_directory / "configs" / "models.yaml").replace(src_directory / "configs" / "models.yaml.orig") + print(f"Original models.yaml file moved to {dest_directory}/configs/models.yaml.orig") + + config_file.replace(config_file.with_suffix("")) + dest_models.replace(dest_models.with_suffix("")) + + def main(): - parser = argparse.ArgumentParser(prog="invokeai-migrate3", - description=""" + parser = argparse.ArgumentParser( + prog="invokeai-migrate3", + description=""" This will copy and convert the models directory and the configs/models.yaml from the InvokeAI 2.3 format '--from-directory' root to the InvokeAI 3.0 '--to-directory' root. These may be abbreviated '--from' and '--to'.a The old models directory and config file will be renamed 'models.orig' and 'models.yaml.orig' respectively. It is safe to provide the same directory for both arguments, but it is better to use the invokeai_configure -script, which will perform a full upgrade in place.""" - ) - parser.add_argument('--from-directory', - dest='src_root', - type=Path, - required=True, - help='Source InvokeAI 2.3 root directory (containing "invokeai.init" or "invokeai.yaml")' - ) - parser.add_argument('--to-directory', - dest='dest_root', - type=Path, - required=True, - help='Destination InvokeAI 3.0 directory (containing "invokeai.yaml")' - ) +script, which will perform a full upgrade in place.""", + ) + parser.add_argument( + "--from-directory", + dest="src_root", + type=Path, + required=True, + help='Source InvokeAI 2.3 root directory (containing "invokeai.init" or "invokeai.yaml")', + ) + parser.add_argument( + "--to-directory", + dest="dest_root", + type=Path, + required=True, + help='Destination InvokeAI 3.0 directory (containing "invokeai.yaml")', + ) args = parser.parse_args() src_root = args.src_root assert src_root.is_dir(), f"{src_root} is not a valid directory" - assert (src_root / 'models').is_dir(), f"{src_root} does not contain a 'models' subdirectory" - assert (src_root / 'models' / 'hub').exists(), f"{src_root} does not contain a version 2.3 models directory" - assert (src_root / 'invokeai.init').exists() or (src_root / 'invokeai.yaml').exists(), f"{src_root} does not contain an InvokeAI init file." + assert (src_root / "models").is_dir(), f"{src_root} does not contain a 'models' subdirectory" + assert (src_root / "models" / "hub").exists(), f"{src_root} does not contain a version 2.3 models directory" + assert (src_root / "invokeai.init").exists() or ( + src_root / "invokeai.yaml" + ).exists(), f"{src_root} does not contain an InvokeAI init file." dest_root = args.dest_root assert dest_root.is_dir(), f"{dest_root} is not a valid directory" config = InvokeAIAppConfig.get_config() - config.parse_args(['--root',str(dest_root)]) + config.parse_args(["--root", str(dest_root)]) # TODO: revisit - don't rely on invokeai.yaml to exist yet! - dest_is_setup = (dest_root / 'models/core').exists() and (dest_root / 'databases').exists() + dest_is_setup = (dest_root / "models/core").exists() and (dest_root / "databases").exists() if not dest_is_setup: import invokeai.frontend.install.invokeai_configure from invokeai.backend.install.invokeai_configure import initialize_rootdir + initialize_rootdir(dest_root, True) - do_migrate(src_root,dest_root) + do_migrate(src_root, dest_root) -if __name__ == '__main__': + +if __name__ == "__main__": main() - - - diff --git a/invokeai/backend/install/model_install_backend.py b/invokeai/backend/install/model_install_backend.py index 26d37a7cbf..b3ab88b5dd 100644 --- a/invokeai/backend/install/model_install_backend.py +++ b/invokeai/backend/install/model_install_backend.py @@ -4,7 +4,7 @@ Utility (backend) functions used by model_install.py import os import shutil import warnings -from dataclasses import dataclass,field +from dataclasses import dataclass, field from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Dict, Callable, Union, Set @@ -28,7 +28,7 @@ warnings.filterwarnings("ignore") # --------------------------globals----------------------- config = InvokeAIAppConfig.get_config() -logger = InvokeAILogger.getLogger(name='InvokeAI') +logger = InvokeAILogger.getLogger(name="InvokeAI") # the initial "configs" dir is now bundled in the `invokeai.configs` package Dataset_path = Path(configs.__path__[0]) / "INITIAL_MODELS.yaml" @@ -45,59 +45,63 @@ Config_preamble = """ LEGACY_CONFIGS = { BaseModelType.StableDiffusion1: { - ModelVariantType.Normal: 'v1-inference.yaml', - ModelVariantType.Inpaint: 'v1-inpainting-inference.yaml', + ModelVariantType.Normal: "v1-inference.yaml", + ModelVariantType.Inpaint: "v1-inpainting-inference.yaml", }, - BaseModelType.StableDiffusion2: { ModelVariantType.Normal: { - SchedulerPredictionType.Epsilon: 'v2-inference.yaml', - SchedulerPredictionType.VPrediction: 'v2-inference-v.yaml', + SchedulerPredictionType.Epsilon: "v2-inference.yaml", + SchedulerPredictionType.VPrediction: "v2-inference-v.yaml", }, ModelVariantType.Inpaint: { - SchedulerPredictionType.Epsilon: 'v2-inpainting-inference.yaml', - SchedulerPredictionType.VPrediction: 'v2-inpainting-inference-v.yaml', - } + SchedulerPredictionType.Epsilon: "v2-inpainting-inference.yaml", + SchedulerPredictionType.VPrediction: "v2-inpainting-inference-v.yaml", + }, }, - BaseModelType.StableDiffusionXL: { - ModelVariantType.Normal: 'sd_xl_base.yaml', + ModelVariantType.Normal: "sd_xl_base.yaml", }, - BaseModelType.StableDiffusionXLRefiner: { - ModelVariantType.Normal: 'sd_xl_refiner.yaml', + ModelVariantType.Normal: "sd_xl_refiner.yaml", }, } + @dataclass class ModelInstallList: - '''Class for listing models to be installed/removed''' + """Class for listing models to be installed/removed""" + install_models: List[str] = field(default_factory=list) remove_models: List[str] = field(default_factory=list) -@dataclass -class InstallSelections(): - install_models: List[str]= field(default_factory=list) - remove_models: List[str]=field(default_factory=list) @dataclass -class ModelLoadInfo(): +class InstallSelections: + install_models: List[str] = field(default_factory=list) + remove_models: List[str] = field(default_factory=list) + + +@dataclass +class ModelLoadInfo: name: str model_type: ModelType base_type: BaseModelType path: Path = None repo_id: str = None - description: str = '' + description: str = "" installed: bool = False recommended: bool = False default: bool = False + class ModelInstall(object): - def __init__(self, - config:InvokeAIAppConfig, - prediction_type_helper: Callable[[Path],SchedulerPredictionType]=None, - model_manager: ModelManager = None, - access_token:str = None): + def __init__( + self, + config: InvokeAIAppConfig, + prediction_type_helper: Callable[[Path], SchedulerPredictionType] = None, + model_manager: ModelManager = None, + access_token: str = None, + ): self.config = config self.mgr = model_manager or ModelManager(config.model_conf_path) self.datasets = OmegaConf.load(Dataset_path) @@ -105,66 +109,66 @@ class ModelInstall(object): self.access_token = access_token or HfFolder.get_token() self.reverse_paths = self._reverse_paths(self.datasets) - def all_models(self)->Dict[str,ModelLoadInfo]: - ''' + def all_models(self) -> Dict[str, ModelLoadInfo]: + """ Return dict of model_key=>ModelLoadInfo objects. This method consolidates and simplifies the entries in both models.yaml and INITIAL_MODELS.yaml so that they can be treated uniformly. It also sorts the models alphabetically by their name, to improve the display somewhat. - ''' + """ model_dict = dict() - + # first populate with the entries in INITIAL_MODELS.yaml for key, value in self.datasets.items(): - name,base,model_type = ModelManager.parse_key(key) - value['name'] = name - value['base_type'] = base - value['model_type'] = model_type + name, base, model_type = ModelManager.parse_key(key) + value["name"] = name + value["base_type"] = base + value["model_type"] = model_type model_dict[key] = ModelLoadInfo(**value) # supplement with entries in models.yaml installed_models = self.mgr.list_models() - + for md in installed_models: - base = md['base_model'] - model_type = md['model_type'] - name = md['model_name'] + base = md["base_model"] + model_type = md["model_type"] + name = md["model_name"] key = ModelManager.create_key(name, base, model_type) if key in model_dict: model_dict[key].installed = True else: model_dict[key] = ModelLoadInfo( - name = name, - base_type = base, - model_type = model_type, - path = value.get('path'), - installed = True, + name=name, + base_type=base, + model_type=model_type, + path=value.get("path"), + installed=True, ) - return {x : model_dict[x] for x in sorted(model_dict.keys(),key=lambda y: model_dict[y].name.lower())} + return {x: model_dict[x] for x in sorted(model_dict.keys(), key=lambda y: model_dict[y].name.lower())} def list_models(self, model_type): installed = self.mgr.list_models(model_type=model_type) - print(f'Installed models of type `{model_type}`:') + print(f"Installed models of type `{model_type}`:") for i in installed: print(f"{i['model_name']}\t{i['base_model']}\t{i['path']}") # logic here a little reversed to maintain backward compatibility - def starter_models(self, all_models: bool=False)->Set[str]: + def starter_models(self, all_models: bool = False) -> Set[str]: models = set() for key, value in self.datasets.items(): - name,base,model_type = ModelManager.parse_key(key) - if all_models or model_type==ModelType.Main: + name, base, model_type = ModelManager.parse_key(key) + if all_models or model_type in [ModelType.Main, ModelType.Vae]: models.add(key) return models - def recommended_models(self)->Set[str]: + def recommended_models(self) -> Set[str]: starters = self.starter_models(all_models=True) - return set([x for x in starters if self.datasets[x].get('recommended',False)]) - - def default_model(self)->str: + return set([x for x in starters if self.datasets[x].get("recommended", False)]) + + def default_model(self) -> str: starters = self.starter_models() - defaults = [x for x in starters if self.datasets[x].get('default',False)] + defaults = [x for x in starters if self.datasets[x].get("default", False)] return defaults[0] def install(self, selections: InstallSelections): @@ -173,54 +177,57 @@ class ModelInstall(object): job = 1 jobs = len(selections.remove_models) + len(selections.install_models) - + # remove requested models for key in selections.remove_models: - name,base,mtype = self.mgr.parse_key(key) - logger.info(f'Deleting {mtype} model {name} [{job}/{jobs}]') + name, base, mtype = self.mgr.parse_key(key) + logger.info(f"Deleting {mtype} model {name} [{job}/{jobs}]") try: - self.mgr.del_model(name,base,mtype) + self.mgr.del_model(name, base, mtype) except FileNotFoundError as e: logger.warning(e) job += 1 - + # add requested models for path in selections.install_models: - logger.info(f'Installing {path} [{job}/{jobs}]') + logger.info(f"Installing {path} [{job}/{jobs}]") try: self.heuristic_import(path) except (ValueError, KeyError) as e: logger.error(str(e)) job += 1 - + dlogging.set_verbosity(verbosity) self.mgr.commit() - def heuristic_import(self, - model_path_id_or_url: Union[str,Path], - models_installed: Set[Path]=None, - )->Dict[str, AddModelResult]: - ''' + def heuristic_import( + self, + model_path_id_or_url: Union[str, Path], + models_installed: Set[Path] = None, + ) -> Dict[str, AddModelResult]: + """ :param model_path_id_or_url: A Path to a local model to import, or a string representing its repo_id or URL :param models_installed: Set of installed models, used for recursive invocation Returns a set of dict objects corresponding to newly-created stanzas in models.yaml. - ''' + """ if not models_installed: models_installed = dict() - + # A little hack to allow nested routines to retrieve info on the requested ID self.current_id = model_path_id_or_url path = Path(model_path_id_or_url) # checkpoint file, or similar if path.is_file(): - models_installed.update({str(path):self._install_path(path)}) + models_installed.update({str(path): self._install_path(path)}) # folders style or similar - elif path.is_dir() and any([(path/x).exists() for x in \ - {'config.json','model_index.json','learned_embeds.bin','pytorch_lora_weights.bin'} - ] - ): + elif path.is_dir() and any( + [ + (path / x).exists() + for x in {"config.json", "model_index.json", "learned_embeds.bin", "pytorch_lora_weights.bin"} + ] + ): models_installed.update({str(model_path_id_or_url): self._install_path(path)}) # recursive scan @@ -229,7 +236,7 @@ class ModelInstall(object): self.heuristic_import(child, models_installed=models_installed) # huggingface repo - elif len(str(model_path_id_or_url).split('/')) == 2: + elif len(str(model_path_id_or_url).split("/")) == 2: models_installed.update({str(model_path_id_or_url): self._install_repo(str(model_path_id_or_url))}) # a URL @@ -237,42 +244,43 @@ class ModelInstall(object): models_installed.update({str(model_path_id_or_url): self._install_url(model_path_id_or_url)}) else: - raise KeyError(f'{str(model_path_id_or_url)} is not recognized as a local path, repo ID or URL. Skipping') + raise KeyError(f"{str(model_path_id_or_url)} is not recognized as a local path, repo ID or URL. Skipping") return models_installed # install a model from a local path. The optional info parameter is there to prevent # the model from being probed twice in the event that it has already been probed. - def _install_path(self, path: Path, info: ModelProbeInfo=None)->AddModelResult: - info = info or ModelProbe().heuristic_probe(path,self.prediction_helper) + def _install_path(self, path: Path, info: ModelProbeInfo = None) -> AddModelResult: + info = info or ModelProbe().heuristic_probe(path, self.prediction_helper) if not info: - logger.warning(f'Unable to parse format of {path}') + logger.warning(f"Unable to parse format of {path}") return None model_name = path.stem if path.is_file() else path.name if self.mgr.model_exists(model_name, info.base_type, info.model_type): raise ValueError(f'A model named "{model_name}" is already installed.') - attributes = self._make_attributes(path,info) - return self.mgr.add_model(model_name = model_name, - base_model = info.base_type, - model_type = info.model_type, - model_attributes = attributes, - ) + attributes = self._make_attributes(path, info) + return self.mgr.add_model( + model_name=model_name, + base_model=info.base_type, + model_type=info.model_type, + model_attributes=attributes, + ) - def _install_url(self, url: str)->AddModelResult: + def _install_url(self, url: str) -> AddModelResult: with TemporaryDirectory(dir=self.config.models_path) as staging: - location = download_with_resume(url,Path(staging)) + location = download_with_resume(url, Path(staging)) if not location: - logger.error(f'Unable to download {url}. Skipping.') + logger.error(f"Unable to download {url}. Skipping.") info = ModelProbe().heuristic_probe(location) dest = self.config.models_path / info.base_type.value / info.model_type.value / location.name - models_path = shutil.move(location,dest) + models_path = shutil.move(location, dest) # staged version will be garbage-collected at this time return self._install_path(Path(models_path), info) - def _install_repo(self, repo_id: str)->AddModelResult: + def _install_repo(self, repo_id: str) -> AddModelResult: hinfo = HfApi().model_info(repo_id) - + # we try to figure out how to download this most economically # list all the files in the repo files = [x.rfilename for x in hinfo.siblings] @@ -280,42 +288,49 @@ class ModelInstall(object): with TemporaryDirectory(dir=self.config.models_path) as staging: staging = Path(staging) - if 'model_index.json' in files: - location = self._download_hf_pipeline(repo_id, staging) # pipeline + if "model_index.json" in files: + location = self._download_hf_pipeline(repo_id, staging) # pipeline else: - for suffix in ['safetensors','bin']: - if f'pytorch_lora_weights.{suffix}' in files: - location = self._download_hf_model(repo_id, ['pytorch_lora_weights.bin'], staging) # LoRA + for suffix in ["safetensors", "bin"]: + if f"pytorch_lora_weights.{suffix}" in files: + location = self._download_hf_model(repo_id, ["pytorch_lora_weights.bin"], staging) # LoRA break - elif self.config.precision=='float16' and f'diffusion_pytorch_model.fp16.{suffix}' in files: # vae, controlnet or some other standalone - files = ['config.json', f'diffusion_pytorch_model.fp16.{suffix}'] + elif ( + self.config.precision == "float16" and f"diffusion_pytorch_model.fp16.{suffix}" in files + ): # vae, controlnet or some other standalone + files = ["config.json", f"diffusion_pytorch_model.fp16.{suffix}"] location = self._download_hf_model(repo_id, files, staging) break - elif f'diffusion_pytorch_model.{suffix}' in files: - files = ['config.json', f'diffusion_pytorch_model.{suffix}'] + elif f"diffusion_pytorch_model.{suffix}" in files: + files = ["config.json", f"diffusion_pytorch_model.{suffix}"] location = self._download_hf_model(repo_id, files, staging) break - elif f'learned_embeds.{suffix}' in files: - location = self._download_hf_model(repo_id, [f'learned_embeds.{suffix}'], staging) + elif f"learned_embeds.{suffix}" in files: + location = self._download_hf_model(repo_id, [f"learned_embeds.{suffix}"], staging) break if not location: - logger.warning(f'Could not determine type of repo {repo_id}. Skipping install.') + logger.warning(f"Could not determine type of repo {repo_id}. Skipping install.") return {} info = ModelProbe().heuristic_probe(location, self.prediction_helper) if not info: - logger.warning(f'Could not probe {location}. Skipping install.') + logger.warning(f"Could not probe {location}. Skipping install.") return {} - dest = self.config.models_path / info.base_type.value / info.model_type.value / self._get_model_name(repo_id,location) + dest = ( + self.config.models_path + / info.base_type.value + / info.model_type.value + / self._get_model_name(repo_id, location) + ) if dest.exists(): shutil.rmtree(dest) - shutil.copytree(location,dest) + shutil.copytree(location, dest) return self._install_path(dest, info) - def _get_model_name(self,path_name: str, location: Path)->str: - ''' + def _get_model_name(self, path_name: str, location: Path) -> str: + """ Calculate a name for the model - primitive implementation. - ''' + """ if key := self.reverse_paths.get(path_name): (name, base, mtype) = ModelManager.parse_key(key) return name @@ -324,99 +339,103 @@ class ModelInstall(object): else: return location.stem - def _make_attributes(self, path: Path, info: ModelProbeInfo)->dict: + def _make_attributes(self, path: Path, info: ModelProbeInfo) -> dict: model_name = path.name if path.is_dir() else path.stem - description = f'{info.base_type.value} {info.model_type.value} model {model_name}' + description = f"{info.base_type.value} {info.model_type.value} model {model_name}" if key := self.reverse_paths.get(self.current_id): if key in self.datasets: - description = self.datasets[key].get('description') or description + description = self.datasets[key].get("description") or description rel_path = self.relative_to_root(path) attributes = dict( - path = str(rel_path), - description = str(description), - model_format = info.format, - ) + path=str(rel_path), + description=str(description), + model_format=info.format, + ) legacy_conf = None if info.model_type == ModelType.Main: - attributes.update(dict(variant = info.variant_type,)) - if info.format=="checkpoint": + attributes.update( + dict( + variant=info.variant_type, + ) + ) + if info.format == "checkpoint": try: - possible_conf = path.with_suffix('.yaml') + possible_conf = path.with_suffix(".yaml") if possible_conf.exists(): legacy_conf = str(self.relative_to_root(possible_conf)) elif info.base_type == BaseModelType.StableDiffusion2: - legacy_conf = Path(self.config.legacy_conf_dir, LEGACY_CONFIGS[info.base_type][info.variant_type][info.prediction_type]) + legacy_conf = Path( + self.config.legacy_conf_dir, + LEGACY_CONFIGS[info.base_type][info.variant_type][info.prediction_type], + ) else: - legacy_conf = Path(self.config.legacy_conf_dir, LEGACY_CONFIGS[info.base_type][info.variant_type]) + legacy_conf = Path( + self.config.legacy_conf_dir, LEGACY_CONFIGS[info.base_type][info.variant_type] + ) except KeyError: - legacy_conf = Path(self.config.legacy_conf_dir, 'v1-inference.yaml') # best guess - - if info.model_type == ModelType.ControlNet and info.format=="checkpoint": - possible_conf = path.with_suffix('.yaml') + legacy_conf = Path(self.config.legacy_conf_dir, "v1-inference.yaml") # best guess + + if info.model_type == ModelType.ControlNet and info.format == "checkpoint": + possible_conf = path.with_suffix(".yaml") if possible_conf.exists(): legacy_conf = str(self.relative_to_root(possible_conf)) if legacy_conf: - attributes.update( - dict( - config = str(legacy_conf) - ) - ) + attributes.update(dict(config=str(legacy_conf))) return attributes - def relative_to_root(self, path: Path)->Path: + def relative_to_root(self, path: Path) -> Path: root = self.config.root_path if path.is_relative_to(root): return path.relative_to(root) else: return path - def _download_hf_pipeline(self, repo_id: str, staging: Path)->Path: - ''' + def _download_hf_pipeline(self, repo_id: str, staging: Path) -> Path: + """ This retrieves a StableDiffusion model from cache or remote and then does a save_pretrained() to the indicated staging area. - ''' - _,name = repo_id.split("/") - revisions = ['fp16','main'] if self.config.precision=='float16' else ['main'] + """ + _, name = repo_id.split("/") + revisions = ["fp16", "main"] if self.config.precision == "float16" else ["main"] model = None for revision in revisions: try: - model = DiffusionPipeline.from_pretrained(repo_id,revision=revision,safety_checker=None) + model = DiffusionPipeline.from_pretrained(repo_id, revision=revision, safety_checker=None) except: # most errors are due to fp16 not being present. Fix this to catch other errors pass if model: break if not model: - logger.error(f'Diffusers model {repo_id} could not be downloaded. Skipping.') + logger.error(f"Diffusers model {repo_id} could not be downloaded. Skipping.") return None model.save_pretrained(staging / name, safe_serialization=True) return staging / name - def _download_hf_model(self, repo_id: str, files: List[str], staging: Path)->Path: - _,name = repo_id.split("/") + def _download_hf_model(self, repo_id: str, files: List[str], staging: Path) -> Path: + _, name = repo_id.split("/") location = staging / name paths = list() for filename in files: - p = hf_download_with_resume(repo_id, - model_dir=location, - model_name=filename, - access_token = self.access_token - ) + p = hf_download_with_resume( + repo_id, model_dir=location, model_name=filename, access_token=self.access_token + ) if p: paths.append(p) else: - logger.warning(f'Could not download {filename} from {repo_id}.') - - return location if len(paths)>0 else None + logger.warning(f"Could not download {filename} from {repo_id}.") + + return location if len(paths) > 0 else None @classmethod - def _reverse_paths(cls,datasets)->dict: - ''' + def _reverse_paths(cls, datasets) -> dict: + """ Reverse mapping from repo_id/path to destination name. - ''' - return {v.get('path') or v.get('repo_id') : k for k, v in datasets.items()} + """ + return {v.get("path") or v.get("repo_id"): k for k, v in datasets.items()} + # ------------------------------------- def yes_or_no(prompt: str, default_yes=True): @@ -427,13 +446,12 @@ def yes_or_no(prompt: str, default_yes=True): else: return response[0] in ("y", "Y") + # --------------------------------------------- -def hf_download_from_pretrained( - model_class: object, model_name: str, destination: Path, **kwargs -): - logger = InvokeAILogger.getLogger('InvokeAI') - logger.addFilter(lambda x: 'fp16 is not a valid' not in x.getMessage()) - +def hf_download_from_pretrained(model_class: object, model_name: str, destination: Path, **kwargs): + logger = InvokeAILogger.getLogger("InvokeAI") + logger.addFilter(lambda x: "fp16 is not a valid" not in x.getMessage()) + model = model_class.from_pretrained( model_name, resume_download=True, @@ -442,13 +460,14 @@ def hf_download_from_pretrained( model.save_pretrained(destination, safe_serialization=True) return destination + # --------------------------------------------- def hf_download_with_resume( - repo_id: str, - model_dir: str, - model_name: str, - model_dest: Path = None, - access_token: str = None, + repo_id: str, + model_dir: str, + model_name: str, + model_dest: Path = None, + access_token: str = None, ) -> Path: model_dest = model_dest or Path(os.path.join(model_dir, model_name)) os.makedirs(model_dir, exist_ok=True) @@ -467,9 +486,7 @@ def hf_download_with_resume( resp = requests.get(url, headers=header, stream=True) total = int(resp.headers.get("content-length", 0)) - if ( - resp.status_code == 416 - ): # "range not satisfiable", which means nothing to return + if resp.status_code == 416: # "range not satisfiable", which means nothing to return logger.info(f"{model_name}: complete file found. Skipping.") return model_dest elif resp.status_code == 404: @@ -498,5 +515,3 @@ def hf_download_with_resume( logger.error(f"An error occurred while downloading {model_name}: {str(e)}") return None return model_dest - - diff --git a/invokeai/backend/model_management/__init__.py b/invokeai/backend/model_management/__init__.py index 91180d4474..a277ecb29c 100644 --- a/invokeai/backend/model_management/__init__.py +++ b/invokeai/backend/model_management/__init__.py @@ -3,6 +3,12 @@ Initialization file for invokeai.backend.model_management """ from .model_manager import ModelManager, ModelInfo, AddModelResult, SchedulerPredictionType from .model_cache import ModelCache -from .models import BaseModelType, ModelType, SubModelType, ModelVariantType, ModelNotFoundException, DuplicateModelException +from .models import ( + BaseModelType, + ModelType, + SubModelType, + ModelVariantType, + ModelNotFoundException, + DuplicateModelException, +) from .model_merge import ModelMerger, MergeInterpolationMethod - diff --git a/invokeai/backend/model_management/convert_ckpt_to_diffusers.py b/invokeai/backend/model_management/convert_ckpt_to_diffusers.py index 0124da7f56..2c62b8b192 100644 --- a/invokeai/backend/model_management/convert_ckpt_to_diffusers.py +++ b/invokeai/backend/model_management/convert_ckpt_to_diffusers.py @@ -56,9 +56,7 @@ from diffusers.schedulers import ( ) from diffusers.utils import is_accelerate_available, is_omegaconf_available, is_safetensors_available from diffusers.utils.import_utils import BACKENDS_MAPPING -from diffusers.pipelines.latent_diffusion.pipeline_latent_diffusion import ( - LDMBertConfig, LDMBertModel -) +from diffusers.pipelines.latent_diffusion.pipeline_latent_diffusion import LDMBertConfig, LDMBertModel from diffusers.pipelines.paint_by_example import PaintByExampleImageEncoder from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker @@ -85,6 +83,7 @@ if is_accelerate_available(): logger = InvokeAILogger.getLogger(__name__) CONVERT_MODEL_ROOT = InvokeAIAppConfig.get_config().root_path / MODEL_CORE / "convert" + def shave_segments(path, n_shave_prefix_segments=1): """ Removes segments. Positive values shave the first segments, negative shave the last segments. @@ -509,9 +508,7 @@ def convert_ldm_unet_checkpoint( paths = renew_resnet_paths(resnets) meta_path = {"old": f"input_blocks.{i}.0", "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}"} - assign_to_checkpoint( - paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config - ) + assign_to_checkpoint(paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config) if len(attentions): paths = renew_attention_paths(attentions) @@ -796,7 +793,7 @@ def convert_ldm_bert_checkpoint(checkpoint, config): def convert_ldm_clip_checkpoint(checkpoint, local_files_only=False, text_encoder=None): if text_encoder is None: - config = CLIPTextConfig.from_pretrained(CONVERT_MODEL_ROOT / 'clip-vit-large-patch14') + config = CLIPTextConfig.from_pretrained(CONVERT_MODEL_ROOT / "clip-vit-large-patch14") ctx = init_empty_weights if is_accelerate_available() else nullcontext with ctx(): @@ -1008,7 +1005,9 @@ def stable_unclip_image_encoder(original_config): elif sd_clip_image_embedder_class == "FrozenOpenCLIPImageEmbedder": feature_extractor = CLIPImageProcessor() # InvokeAI doesn't use CLIPVisionModelWithProjection so it isn't in the core - if this code is hit a download will occur - image_encoder = CLIPVisionModelWithProjection.from_pretrained(CONVERT_MODEL_ROOT / "CLIP-ViT-H-14-laion2B-s32B-b79K") + image_encoder = CLIPVisionModelWithProjection.from_pretrained( + CONVERT_MODEL_ROOT / "CLIP-ViT-H-14-laion2B-s32B-b79K" + ) else: raise NotImplementedError( f"Unknown CLIP image embedder class in stable diffusion checkpoint {sd_clip_image_embedder_class}" @@ -1071,17 +1070,17 @@ def convert_controlnet_checkpoint( extract_ema, use_linear_projection=None, cross_attention_dim=None, - precision: torch.dtype=torch.float32, + precision: torch.dtype = torch.float32, ): ctrlnet_config = create_unet_diffusers_config(original_config, image_size=image_size, controlnet=True) ctrlnet_config["upcast_attention"] = upcast_attention ctrlnet_config.pop("sample_size") original_config = ctrlnet_config.copy() - - ctrlnet_config.pop('addition_embed_type') - ctrlnet_config.pop('addition_time_embed_dim') - ctrlnet_config.pop('transformer_layers_per_block') + + ctrlnet_config.pop("addition_embed_type") + ctrlnet_config.pop("addition_time_embed_dim") + ctrlnet_config.pop("transformer_layers_per_block") if use_linear_projection is not None: ctrlnet_config["use_linear_projection"] = use_linear_projection @@ -1111,6 +1110,7 @@ def convert_controlnet_checkpoint( return controlnet.to(precision) + # TO DO - PASS PRECISION def download_from_original_stable_diffusion_ckpt( checkpoint_path: str, @@ -1249,8 +1249,8 @@ def download_from_original_stable_diffusion_ckpt( # "state_dict" key https://huggingface.co/thibaud/controlnet-canny-sd21 while "state_dict" in checkpoint: checkpoint = checkpoint["state_dict"] - - logger.debug(f'model_type = {model_type}; original_config_file = {original_config_file}') + + logger.debug(f"model_type = {model_type}; original_config_file = {original_config_file}") if original_config_file is None: key_name_v2_1 = "model.diffusion_model.input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight" @@ -1258,7 +1258,9 @@ def download_from_original_stable_diffusion_ckpt( key_name_sd_xl_refiner = "conditioner.embedders.0.model.transformer.resblocks.9.mlp.c_proj.bias" # model_type = "v1" - config_url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml" + config_url = ( + "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml" + ) if key_name_v2_1 in checkpoint and checkpoint[key_name_v2_1].shape[-1] == 1024: # model_type = "v2" @@ -1277,7 +1279,10 @@ def download_from_original_stable_diffusion_ckpt( original_config_file = BytesIO(requests.get(config_url).content) original_config = OmegaConf.load(original_config_file) - if model_version == BaseModelType.StableDiffusion2 and original_config["model"]["params"]["parameterization"] == "v": + if ( + model_version == BaseModelType.StableDiffusion2 + and original_config["model"]["params"]["parameterization"] == "v" + ): prediction_type = "v_prediction" upcast_attention = True image_size = 768 @@ -1436,7 +1441,7 @@ def download_from_original_stable_diffusion_ckpt( config_kwargs = {"subfolder": "text_encoder"} text_model = convert_open_clip_checkpoint(checkpoint, config_name, **config_kwargs) - tokenizer = CLIPTokenizer.from_pretrained(CONVERT_MODEL_ROOT / 'stable-diffusion-2-clip', subfolder="tokenizer") + tokenizer = CLIPTokenizer.from_pretrained(CONVERT_MODEL_ROOT / "stable-diffusion-2-clip", subfolder="tokenizer") if stable_unclip is None: if controlnet: @@ -1491,7 +1496,9 @@ def download_from_original_stable_diffusion_ckpt( prior = PriorTransformer.from_pretrained(karlo_model, subfolder="prior") prior_tokenizer = CLIPTokenizer.from_pretrained(CONVERT_MODEL_ROOT / "clip-vit-large-patch14") - prior_text_model = CLIPTextModelWithProjection.from_pretrained(CONVERT_MODEL_ROOT / "clip-vit-large-patch14") + prior_text_model = CLIPTextModelWithProjection.from_pretrained( + CONVERT_MODEL_ROOT / "clip-vit-large-patch14" + ) prior_scheduler = UnCLIPScheduler.from_pretrained(karlo_model, subfolder="prior_scheduler") prior_scheduler = DDPMScheduler.from_config(prior_scheduler.config) @@ -1533,11 +1540,19 @@ def download_from_original_stable_diffusion_ckpt( text_model = convert_ldm_clip_checkpoint( checkpoint, local_files_only=local_files_only, text_encoder=text_encoder ) - tokenizer = CLIPTokenizer.from_pretrained(CONVERT_MODEL_ROOT / "clip-vit-large-patch14") if tokenizer is None else tokenizer + tokenizer = ( + CLIPTokenizer.from_pretrained(CONVERT_MODEL_ROOT / "clip-vit-large-patch14") + if tokenizer is None + else tokenizer + ) if load_safety_checker: - safety_checker = StableDiffusionSafetyChecker.from_pretrained(CONVERT_MODEL_ROOT / "stable-diffusion-safety-checker") - feature_extractor = AutoFeatureExtractor.from_pretrained(CONVERT_MODEL_ROOT / "stable-diffusion-safety-checker") + safety_checker = StableDiffusionSafetyChecker.from_pretrained( + CONVERT_MODEL_ROOT / "stable-diffusion-safety-checker" + ) + feature_extractor = AutoFeatureExtractor.from_pretrained( + CONVERT_MODEL_ROOT / "stable-diffusion-safety-checker" + ) else: safety_checker = None feature_extractor = None @@ -1567,7 +1582,7 @@ def download_from_original_stable_diffusion_ckpt( if model_type == "SDXL": tokenizer = CLIPTokenizer.from_pretrained(CONVERT_MODEL_ROOT / "clip-vit-large-patch14") text_encoder = convert_ldm_clip_checkpoint(checkpoint, local_files_only=local_files_only) - + tokenizer_name = CONVERT_MODEL_ROOT / "CLIP-ViT-bigG-14-laion2B-39B-b160k" tokenizer_2 = CLIPTokenizer.from_pretrained(tokenizer_name, pad_token="!") @@ -1577,7 +1592,7 @@ def download_from_original_stable_diffusion_ckpt( checkpoint, config_name, prefix="conditioner.embedders.1.model.", has_projection=True, **config_kwargs ) - pipe = StableDiffusionXLPipeline ( + pipe = StableDiffusionXLPipeline( vae=vae.to(precision), text_encoder=text_encoder, tokenizer=tokenizer, @@ -1686,24 +1701,22 @@ def download_controlnet_from_original_ckpt( return controlnet -def convert_ldm_vae_to_diffusers(checkpoint, vae_config: DictConfig, image_size: int) -> AutoencoderKL: - vae_config = create_vae_diffusers_config( - vae_config, image_size=image_size - ) - converted_vae_checkpoint = convert_ldm_vae_checkpoint( - checkpoint, vae_config - ) +def convert_ldm_vae_to_diffusers(checkpoint, vae_config: DictConfig, image_size: int) -> AutoencoderKL: + vae_config = create_vae_diffusers_config(vae_config, image_size=image_size) + + converted_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config) vae = AutoencoderKL(**vae_config) vae.load_state_dict(converted_vae_checkpoint) return vae + def convert_ckpt_to_diffusers( - checkpoint_path: Union[str, Path], - dump_path: Union[str, Path], - use_safetensors: bool=True, - **kwargs, + checkpoint_path: Union[str, Path], + dump_path: Union[str, Path], + use_safetensors: bool = True, + **kwargs, ): """ Takes all the arguments of download_from_original_stable_diffusion_ckpt(), @@ -1717,10 +1730,11 @@ def convert_ckpt_to_diffusers( safe_serialization=use_safetensors and is_safetensors_available(), ) + def convert_controlnet_to_diffusers( - checkpoint_path: Union[str, Path], - dump_path: Union[str, Path], - **kwargs, + checkpoint_path: Union[str, Path], + dump_path: Union[str, Path], + **kwargs, ): """ Takes all the arguments of download_controlnet_from_original_ckpt(), diff --git a/invokeai/backend/model_management/lora.py b/invokeai/backend/model_management/lora.py index 222169afbb..06770843ec 100644 --- a/invokeai/backend/model_management/lora.py +++ b/invokeai/backend/model_management/lora.py @@ -11,14 +11,15 @@ from diffusers.models import UNet2DConditionModel from safetensors.torch import load_file from transformers import CLIPTextModel, CLIPTokenizer -class LoRALayerBase: - #rank: Optional[int] - #alpha: Optional[float] - #bias: Optional[torch.Tensor] - #layer_key: str - #@property - #def scale(self): +class LoRALayerBase: + # rank: Optional[int] + # alpha: Optional[float] + # bias: Optional[torch.Tensor] + # layer_key: str + + # @property + # def scale(self): # return self.alpha / self.rank if (self.alpha and self.rank) else 1.0 def __init__( @@ -31,11 +32,7 @@ class LoRALayerBase: else: self.alpha = None - if ( - "bias_indices" in values - and "bias_values" in values - and "bias_size" in values - ): + if "bias_indices" in values and "bias_values" in values and "bias_size" in values: self.bias = torch.sparse_coo_tensor( values["bias_indices"], values["bias_values"], @@ -45,13 +42,13 @@ class LoRALayerBase: else: self.bias = None - self.rank = None # set in layer implementation + self.rank = None # set in layer implementation self.layer_key = layer_key def forward( self, module: torch.nn.Module, - input_h: Any, # for real looks like Tuple[torch.nn.Tensor] but not sure + input_h: Any, # for real looks like Tuple[torch.nn.Tensor] but not sure multiplier: float, ): if type(module) == torch.nn.Conv2d: @@ -71,12 +68,16 @@ class LoRALayerBase: bias = self.bias if self.bias is not None else 0 scale = self.alpha / self.rank if (self.alpha and self.rank) else 1.0 - return op( - *input_h, - (weight + bias).view(module.weight.shape), - None, - **extra_args, - ) * multiplier * scale + return ( + op( + *input_h, + (weight + bias).view(module.weight.shape), + None, + **extra_args, + ) + * multiplier + * scale + ) def get_weight(self): raise NotImplementedError() @@ -99,9 +100,9 @@ class LoRALayerBase: # TODO: find and debug lora/locon with bias class LoRALayer(LoRALayerBase): - #up: torch.Tensor - #mid: Optional[torch.Tensor] - #down: torch.Tensor + # up: torch.Tensor + # mid: Optional[torch.Tensor] + # down: torch.Tensor def __init__( self, @@ -151,12 +152,12 @@ class LoRALayer(LoRALayerBase): class LoHALayer(LoRALayerBase): - #w1_a: torch.Tensor - #w1_b: torch.Tensor - #w2_a: torch.Tensor - #w2_b: torch.Tensor - #t1: Optional[torch.Tensor] = None - #t2: Optional[torch.Tensor] = None + # w1_a: torch.Tensor + # w1_b: torch.Tensor + # w2_a: torch.Tensor + # w2_b: torch.Tensor + # t1: Optional[torch.Tensor] = None + # t2: Optional[torch.Tensor] = None def __init__( self, @@ -187,12 +188,8 @@ class LoHALayer(LoRALayerBase): weight = (self.w1_a @ self.w1_b) * (self.w2_a @ self.w2_b) else: - rebuild1 = torch.einsum( - "i j k l, j r, i p -> p r k l", self.t1, self.w1_b, self.w1_a - ) - rebuild2 = torch.einsum( - "i j k l, j r, i p -> p r k l", self.t2, self.w2_b, self.w2_a - ) + rebuild1 = torch.einsum("i j k l, j r, i p -> p r k l", self.t1, self.w1_b, self.w1_a) + rebuild2 = torch.einsum("i j k l, j r, i p -> p r k l", self.t2, self.w2_b, self.w2_a) weight = rebuild1 * rebuild2 return weight @@ -223,20 +220,20 @@ class LoHALayer(LoRALayerBase): class LoKRLayer(LoRALayerBase): - #w1: Optional[torch.Tensor] = None - #w1_a: Optional[torch.Tensor] = None - #w1_b: Optional[torch.Tensor] = None - #w2: Optional[torch.Tensor] = None - #w2_a: Optional[torch.Tensor] = None - #w2_b: Optional[torch.Tensor] = None - #t2: Optional[torch.Tensor] = None + # w1: Optional[torch.Tensor] = None + # w1_a: Optional[torch.Tensor] = None + # w1_b: Optional[torch.Tensor] = None + # w2: Optional[torch.Tensor] = None + # w2_a: Optional[torch.Tensor] = None + # w2_b: Optional[torch.Tensor] = None + # t2: Optional[torch.Tensor] = None def __init__( self, layer_key: str, values: dict, ): - super().__init__(layer_key, values) + super().__init__(layer_key, values) if "lokr_w1" in values: self.w1 = values["lokr_w1"] @@ -266,7 +263,7 @@ class LoKRLayer(LoRALayerBase): elif "lokr_w2_b" in values: self.rank = values["lokr_w2_b"].shape[0] else: - self.rank = None # unscaled + self.rank = None # unscaled def get_weight(self): w1 = self.w1 @@ -278,7 +275,7 @@ class LoKRLayer(LoRALayerBase): if self.t2 is None: w2 = self.w2_a @ self.w2_b else: - w2 = torch.einsum('i j k l, i p, j r -> p r k l', self.t2, self.w2_a, self.w2_b) + w2 = torch.einsum("i j k l, i p, j r -> p r k l", self.t2, self.w2_a, self.w2_b) if len(w2.shape) == 4: w1 = w1.unsqueeze(2).unsqueeze(2) @@ -317,7 +314,7 @@ class LoKRLayer(LoRALayerBase): self.t2 = self.t2.to(device=device, dtype=dtype) -class LoRAModel: #(torch.nn.Module): +class LoRAModel: # (torch.nn.Module): _name: str layers: Dict[str, LoRALayer] _device: torch.device @@ -345,7 +342,7 @@ class LoRAModel: #(torch.nn.Module): @property def dtype(self): - return self._dtype + return self._dtype def to( self, @@ -380,7 +377,7 @@ class LoRAModel: #(torch.nn.Module): model = cls( device=device, dtype=dtype, - name=file_path.stem, # TODO: + name=file_path.stem, # TODO: layers=dict(), ) @@ -392,7 +389,6 @@ class LoRAModel: #(torch.nn.Module): state_dict = cls._group_state(state_dict) for layer_key, values in state_dict.items(): - # lora and locon if "lora_down.weight" in values: layer = LoRALayer(layer_key, values) @@ -407,9 +403,7 @@ class LoRAModel: #(torch.nn.Module): else: # TODO: diff/ia3/... format - print( - f">> Encountered unknown lora layer module in {model.name}: {layer_key}" - ) + print(f">> Encountered unknown lora layer module in {model.name}: {layer_key}") return # lower memory consumption by removing already parsed layer values @@ -443,9 +437,10 @@ with LoRAHelper.apply_lora_unet(unet, loras): # unmodified unet """ + + # TODO: rename smth like ModelPatcher and add TI method? class ModelPatcher: - @staticmethod def _resolve_lora_key(model: torch.nn.Module, lora_key: str, prefix: str) -> Tuple[str, torch.nn.Module]: assert "." not in lora_key @@ -455,10 +450,10 @@ class ModelPatcher: module = model module_key = "" - key_parts = lora_key[len(prefix):].split('_') + key_parts = lora_key[len(prefix) :].split("_") submodule_name = key_parts.pop(0) - + while len(key_parts) > 0: try: module = module.get_submodule(submodule_name) @@ -477,7 +472,6 @@ class ModelPatcher: applied_loras: List[Tuple[LoRAModel, float]], layer_name: str, ): - def lora_forward(module, input_h, output): if len(applied_loras) == 0: return output @@ -491,7 +485,6 @@ class ModelPatcher: return lora_forward - @classmethod @contextmanager def apply_lora_unet( @@ -502,7 +495,6 @@ class ModelPatcher: with cls.apply_lora(unet, loras, "lora_unet_"): yield - @classmethod @contextmanager def apply_lora_text_encoder( @@ -513,7 +505,6 @@ class ModelPatcher: with cls.apply_lora(text_encoder, loras, "lora_te_"): yield - @classmethod @contextmanager def apply_lora( @@ -526,7 +517,7 @@ class ModelPatcher: try: with torch.no_grad(): for lora, lora_weight in loras: - #assert lora.device.type == "cpu" + # assert lora.device.type == "cpu" for layer_key, layer in lora.layers.items(): if not layer_key.startswith(prefix): continue @@ -536,7 +527,7 @@ class ModelPatcher: original_weights[module_key] = module.weight.detach().to(device="cpu", copy=True) # enable autocast to calc fp16 loras on cpu - #with torch.autocast(device_type="cpu"): + # with torch.autocast(device_type="cpu"): layer.to(dtype=torch.float32) layer_scale = layer.alpha / layer.rank if (layer.alpha and layer.rank) else 1.0 layer_weight = layer.get_weight() * lora_weight * layer_scale @@ -547,14 +538,13 @@ class ModelPatcher: module.weight += layer_weight.to(device=module.weight.device, dtype=module.weight.dtype) - yield # wait for context manager exit + yield # wait for context manager exit finally: with torch.no_grad(): for module_key, weight in original_weights.items(): model.get_submodule(module_key).weight.copy_(weight) - @classmethod @contextmanager def apply_ti( @@ -602,7 +592,9 @@ class ModelPatcher: f"Cannot load embedding for {trigger}. It was trained on a model with token dimension {embedding.shape[0]}, but the current model has token dimension {model_embeddings.weight.data[token_id].shape[0]}." ) - model_embeddings.weight.data[token_id] = embedding.to(device=text_encoder.device, dtype=text_encoder.dtype) + model_embeddings.weight.data[token_id] = embedding.to( + device=text_encoder.device, dtype=text_encoder.dtype + ) ti_tokens.append(token_id) if len(ti_tokens) > 1: @@ -614,7 +606,6 @@ class ModelPatcher: if init_tokens_count and new_tokens_added: text_encoder.resize_token_embeddings(init_tokens_count) - @classmethod @contextmanager def apply_clip_skip( @@ -633,9 +624,10 @@ class ModelPatcher: while len(skipped_layers) > 0: text_encoder.text_model.encoder.layers.append(skipped_layers.pop()) + class TextualInversionModel: name: str - embedding: torch.Tensor # [n, 768]|[n, 1280] + embedding: torch.Tensor # [n, 768]|[n, 1280] @classmethod def from_checkpoint( @@ -647,8 +639,8 @@ class TextualInversionModel: if not isinstance(file_path, Path): file_path = Path(file_path) - result = cls() # TODO: - result.name = file_path.stem # TODO: + result = cls() # TODO: + result.name = file_path.stem # TODO: if file_path.suffix == ".safetensors": state_dict = load_file(file_path.absolute().as_posix(), device="cpu") @@ -659,7 +651,9 @@ class TextualInversionModel: # difference mostly in metadata if "string_to_param" in state_dict: if len(state_dict["string_to_param"]) > 1: - print(f"Warn: Embedding \"{file_path.name}\" contains multiple tokens, which is not supported. The first token will be used.") + print( + f'Warn: Embedding "{file_path.name}" contains multiple tokens, which is not supported. The first token will be used.' + ) result.embedding = next(iter(state_dict["string_to_param"].values())) @@ -688,10 +682,7 @@ class TextualInversionManager(BaseTextualInversionManager): self.pad_tokens = dict() self.tokenizer = tokenizer - def expand_textual_inversion_token_ids_if_necessary( - self, token_ids: list[int] - ) -> list[int]: - + def expand_textual_inversion_token_ids_if_necessary(self, token_ids: list[int]) -> list[int]: if len(self.pad_tokens) == 0: return token_ids @@ -707,4 +698,3 @@ class TextualInversionManager(BaseTextualInversionManager): new_token_ids.extend(self.pad_tokens[token_id]) return new_token_ids - diff --git a/invokeai/backend/model_management/model_cache.py b/invokeai/backend/model_management/model_cache.py index 5ca17f00fc..a171c81e3c 100644 --- a/invokeai/backend/model_management/model_cache.py +++ b/invokeai/backend/model_management/model_cache.py @@ -37,19 +37,22 @@ from .models import BaseModelType, ModelType, SubModelType, ModelBase DEFAULT_MAX_CACHE_SIZE = 6.0 # amount of GPU memory to hold in reserve for use by generations (GB) -DEFAULT_MAX_VRAM_CACHE_SIZE= 2.75 +DEFAULT_MAX_VRAM_CACHE_SIZE = 2.75 # actual size of a gig GIG = 1073741824 + class ModelLocker(object): "Forward declaration" pass + class ModelCache(object): "Forward declaration" pass + class _CacheRecord: size: int model: Any @@ -79,22 +82,22 @@ class _CacheRecord: return self.model.device != self.cache.storage_device else: return False - + class ModelCache(object): def __init__( self, - max_cache_size: float=DEFAULT_MAX_CACHE_SIZE, - max_vram_cache_size: float=DEFAULT_MAX_VRAM_CACHE_SIZE, - execution_device: torch.device=torch.device('cuda'), - storage_device: torch.device=torch.device('cpu'), - precision: torch.dtype=torch.float16, - sequential_offload: bool=False, - lazy_offloading: bool=True, + max_cache_size: float = DEFAULT_MAX_CACHE_SIZE, + max_vram_cache_size: float = DEFAULT_MAX_VRAM_CACHE_SIZE, + execution_device: torch.device = torch.device("cuda"), + storage_device: torch.device = torch.device("cpu"), + precision: torch.dtype = torch.float16, + sequential_offload: bool = False, + lazy_offloading: bool = True, sha_chunksize: int = 16777216, - logger: types.ModuleType = logger + logger: types.ModuleType = logger, ): - ''' + """ :param max_cache_size: Maximum size of the RAM cache [6.0 GB] :param execution_device: Torch device to load active model into [torch.device('cuda')] :param storage_device: Torch device to save inactive model in [torch.device('cpu')] @@ -102,16 +105,16 @@ class ModelCache(object): :param lazy_offloading: Keep model in VRAM until another model needs to be loaded :param sequential_offload: Conserve VRAM by loading and unloading each stage of the pipeline sequentially :param sha_chunksize: Chunksize to use when calculating sha256 model hash - ''' + """ self.model_infos: Dict[str, ModelBase] = dict() # allow lazy offloading only when vram cache enabled self.lazy_offloading = lazy_offloading and max_vram_cache_size > 0 - self.precision: torch.dtype=precision - self.max_cache_size: float=max_cache_size - self.max_vram_cache_size: float=max_vram_cache_size - self.execution_device: torch.device=execution_device - self.storage_device: torch.device=storage_device - self.sha_chunksize=sha_chunksize + self.precision: torch.dtype = precision + self.max_cache_size: float = max_cache_size + self.max_vram_cache_size: float = max_vram_cache_size + self.execution_device: torch.device = execution_device + self.storage_device: torch.device = storage_device + self.sha_chunksize = sha_chunksize self.logger = logger self._cached_models = dict() @@ -124,7 +127,6 @@ class ModelCache(object): model_type: ModelType, submodel_type: Optional[SubModelType] = None, ): - key = f"{model_path}:{base_model}:{model_type}" if submodel_type: key += f":{submodel_type}" @@ -163,7 +165,6 @@ class ModelCache(object): submodel: Optional[SubModelType] = None, gpu_load: bool = True, ) -> Any: - if not isinstance(model_path, Path): model_path = Path(model_path) @@ -186,7 +187,7 @@ class ModelCache(object): # TODO: lock for no copies on simultaneous calls? cache_entry = self._cached_models.get(key, None) if cache_entry is None: - self.logger.info(f'Loading model {model_path}, type {base_model}:{model_type}:{submodel}') + self.logger.info(f"Loading model {model_path}, type {base_model}:{model_type}:{submodel}") # this will remove older cached models until # there is sufficient room to load the requested model @@ -196,7 +197,7 @@ class ModelCache(object): gc.collect() model = model_info.get_model(child_type=submodel, torch_dtype=self.precision) if mem_used := model_info.get_size(submodel): - self.logger.debug(f'CPU RAM used for load: {(mem_used/GIG):.2f} GB') + self.logger.debug(f"CPU RAM used for load: {(mem_used/GIG):.2f} GB") cache_entry = _CacheRecord(self, model, mem_used) self._cached_models[key] = cache_entry @@ -209,13 +210,13 @@ class ModelCache(object): class ModelLocker(object): def __init__(self, cache, key, model, gpu_load, size_needed): - ''' + """ :param cache: The model_cache object :param key: The key of the model to lock in GPU :param model: The model to lock :param gpu_load: True if load into gpu :param size_needed: Size of the model to load - ''' + """ self.gpu_load = gpu_load self.cache = cache self.key = key @@ -224,7 +225,7 @@ class ModelCache(object): self.cache_entry = self.cache._cached_models[self.key] def __enter__(self) -> Any: - if not hasattr(self.model, 'to'): + if not hasattr(self.model, "to"): return self.model # NOTE that the model has to have the to() method in order for this @@ -234,22 +235,21 @@ class ModelCache(object): try: if self.cache.lazy_offloading: - self.cache._offload_unlocked_models(self.size_needed) - + self.cache._offload_unlocked_models(self.size_needed) + if self.model.device != self.cache.execution_device: - self.cache.logger.debug(f'Moving {self.key} into {self.cache.execution_device}') + self.cache.logger.debug(f"Moving {self.key} into {self.cache.execution_device}") with VRAMUsage() as mem: self.model.to(self.cache.execution_device) # move into GPU - self.cache.logger.debug(f'GPU VRAM used for load: {(mem.vram_used/GIG):.2f} GB') - - self.cache.logger.debug(f'Locking {self.key} in {self.cache.execution_device}') + self.cache.logger.debug(f"GPU VRAM used for load: {(mem.vram_used/GIG):.2f} GB") + + self.cache.logger.debug(f"Locking {self.key} in {self.cache.execution_device}") self.cache._print_cuda_stats() except: self.cache_entry.unlock() raise - # TODO: not fully understand # in the event that the caller wants the model in RAM, we # move it into CPU if it is in GPU and not locked @@ -259,7 +259,7 @@ class ModelCache(object): return self.model def __exit__(self, type, value, traceback): - if not hasattr(self.model, 'to'): + if not hasattr(self.model, "to"): return self.cache_entry.unlock() @@ -277,11 +277,11 @@ class ModelCache(object): self, model_path: Union[str, Path], ) -> str: - ''' + """ Given the HF repo id or path to a model on disk, returns a unique hash. Works for legacy checkpoint files, HF models on disk, and HF repo IDs :param model_path: Path to model file/directory on disk. - ''' + """ return self._local_model_hash(model_path) def cache_size(self) -> float: @@ -290,7 +290,7 @@ class ModelCache(object): return current_cache_size / GIG def _has_cuda(self) -> bool: - return self.execution_device.type == 'cuda' + return self.execution_device.type == "cuda" def _print_cuda_stats(self): vram = "%4.2fG" % (torch.cuda.memory_allocated() / GIG) @@ -306,18 +306,21 @@ class ModelCache(object): if model_info.locked: locked_models += 1 - self.logger.debug(f"Current VRAM/RAM usage: {vram}/{ram}; cached_models/loaded_models/locked_models/ = {cached_models}/{loaded_models}/{locked_models}") - + self.logger.debug( + f"Current VRAM/RAM usage: {vram}/{ram}; cached_models/loaded_models/locked_models/ = {cached_models}/{loaded_models}/{locked_models}" + ) def _make_cache_room(self, model_size): # calculate how much memory this model will require - #multiplier = 2 if self.precision==torch.float32 else 1 + # multiplier = 2 if self.precision==torch.float32 else 1 bytes_needed = model_size maximum_size = self.max_cache_size * GIG # stored in GB, convert to bytes current_size = sum([m.size for m in self._cached_models.values()]) if current_size + bytes_needed > maximum_size: - self.logger.debug(f'Max cache size exceeded: {(current_size/GIG):.2f}/{self.max_cache_size:.2f} GB, need an additional {(bytes_needed/GIG):.2f} GB') + self.logger.debug( + f"Max cache size exceeded: {(current_size/GIG):.2f}/{self.max_cache_size:.2f} GB, need an additional {(bytes_needed/GIG):.2f} GB" + ) self.logger.debug(f"Before unloading: cached_models={len(self._cached_models)}") @@ -339,7 +342,7 @@ class ModelCache(object): with suppress(RuntimeError): referrer.clear() cleared = True - #break + # break # repeat if referrers changes(due to frame clear), else exit loop if cleared: @@ -348,13 +351,17 @@ class ModelCache(object): break device = cache_entry.model.device if hasattr(cache_entry.model, "device") else None - self.logger.debug(f"Model: {model_key}, locks: {cache_entry._locks}, device: {device}, loaded: {cache_entry.loaded}, refs: {refs}") + self.logger.debug( + f"Model: {model_key}, locks: {cache_entry._locks}, device: {device}, loaded: {cache_entry.loaded}, refs: {refs}" + ) # 2 refs: # 1 from cache_entry # 1 from getrefcount function if not cache_entry.locked and refs <= 2: - self.logger.debug(f'Unloading model {model_key} to free {(model_size/GIG):.2f} GB (-{(cache_entry.size/GIG):.2f} GB)') + self.logger.debug( + f"Unloading model {model_key} to free {(model_size/GIG):.2f} GB (-{(cache_entry.size/GIG):.2f} GB)" + ) current_size -= cache_entry.size del self._cache_stack[pos] del self._cached_models[model_key] @@ -368,38 +375,36 @@ class ModelCache(object): self.logger.debug(f"After unloading: cached_models={len(self._cached_models)}") - def _offload_unlocked_models(self, size_needed: int=0): + def _offload_unlocked_models(self, size_needed: int = 0): reserved = self.max_vram_cache_size * GIG vram_in_use = torch.cuda.memory_allocated() - self.logger.debug(f'{(vram_in_use/GIG):.2f}GB VRAM used for models; max allowed={(reserved/GIG):.2f}GB') - for model_key, cache_entry in sorted(self._cached_models.items(), key=lambda x:x[1].size): + self.logger.debug(f"{(vram_in_use/GIG):.2f}GB VRAM used for models; max allowed={(reserved/GIG):.2f}GB") + for model_key, cache_entry in sorted(self._cached_models.items(), key=lambda x: x[1].size): if vram_in_use <= reserved: break if not cache_entry.locked and cache_entry.loaded: - self.logger.debug(f'Offloading {model_key} from {self.execution_device} into {self.storage_device}') + self.logger.debug(f"Offloading {model_key} from {self.execution_device} into {self.storage_device}") with VRAMUsage() as mem: cache_entry.model.to(self.storage_device) - self.logger.debug(f'GPU VRAM freed: {(mem.vram_used/GIG):.2f} GB') + self.logger.debug(f"GPU VRAM freed: {(mem.vram_used/GIG):.2f} GB") vram_in_use += mem.vram_used # note vram_used is negative - self.logger.debug(f'{(vram_in_use/GIG):.2f}GB VRAM used for models; max allowed={(reserved/GIG):.2f}GB') + self.logger.debug(f"{(vram_in_use/GIG):.2f}GB VRAM used for models; max allowed={(reserved/GIG):.2f}GB") gc.collect() torch.cuda.empty_cache() - + def _local_model_hash(self, model_path: Union[str, Path]) -> str: sha = hashlib.sha256() path = Path(model_path) - + hashpath = path / "checksum.sha256" if hashpath.exists() and path.stat().st_mtime <= hashpath.stat().st_mtime: with open(hashpath) as f: hash = f.read() return hash - - self.logger.debug(f'computing hash of model {path.name}') - for file in list(path.rglob("*.ckpt")) \ - + list(path.rglob("*.safetensors")) \ - + list(path.rglob("*.pth")): + + self.logger.debug(f"computing hash of model {path.name}") + for file in list(path.rglob("*.ckpt")) + list(path.rglob("*.safetensors")) + list(path.rglob("*.pth")): with open(file, "rb") as f: while chunk := f.read(self.sha_chunksize): sha.update(chunk) @@ -408,11 +413,12 @@ class ModelCache(object): f.write(hash) return hash + class VRAMUsage(object): def __init__(self): self.vram = None self.vram_used = 0 - + def __enter__(self): self.vram = torch.cuda.memory_allocated() return self diff --git a/invokeai/backend/model_management/model_manager.py b/invokeai/backend/model_management/model_manager.py index 894fca9d74..2a82061a97 100644 --- a/invokeai/backend/model_management/model_manager.py +++ b/invokeai/backend/model_management/model_manager.py @@ -249,20 +249,26 @@ from invokeai.backend.util import CUDA_DEVICE, Chdir from .model_cache import ModelCache, ModelLocker from .model_search import ModelSearch from .models import ( - BaseModelType, ModelType, SubModelType, - ModelError, SchedulerPredictionType, MODEL_CLASSES, + BaseModelType, + ModelType, + SubModelType, + ModelError, + SchedulerPredictionType, + MODEL_CLASSES, ModelConfigBase, - ModelNotFoundException, InvalidModelException, + ModelNotFoundException, + InvalidModelException, DuplicateModelException, ) # We are only starting to number the config file with release 3. # The config file version doesn't have to start at release version, but it will help # reduce confusion. -CONFIG_FILE_VERSION='3.0.0' +CONFIG_FILE_VERSION = "3.0.0" + @dataclass -class ModelInfo(): +class ModelInfo: context: ModelLocker name: str base_model: BaseModelType @@ -275,20 +281,24 @@ class ModelInfo(): def __enter__(self): return self.context.__enter__() - def __exit__(self,*args, **kwargs): + def __exit__(self, *args, **kwargs): self.context.__exit__(*args, **kwargs) + class AddModelResult(BaseModel): name: str = Field(description="The name of the model after installation") model_type: ModelType = Field(description="The type of model") base_model: BaseModelType = Field(description="The base model") config: ModelConfigBase = Field(description="The configuration of the model") + MAX_CACHE_SIZE = 6.0 # GB + class ConfigMeta(BaseModel): version: str + class ModelManager(object): """ High-level interface to model management. @@ -315,12 +325,12 @@ class ModelManager(object): if isinstance(config, (str, Path)): self.config_path = Path(config) if not self.config_path.exists(): - logger.warning(f'The file {self.config_path} was not found. Initializing a new file') + logger.warning(f"The file {self.config_path} was not found. Initializing a new file") self.initialize_model_config(self.config_path) config = OmegaConf.load(self.config_path) elif not isinstance(config, DictConfig): - raise ValueError('config argument must be an OmegaConf object, a Path or a string') + raise ValueError("config argument must be an OmegaConf object, a Path or a string") self.config_meta = ConfigMeta(**config.pop("__metadata__")) # TODO: metadata not found @@ -330,11 +340,11 @@ class ModelManager(object): self.logger = logger self.cache = ModelCache( max_cache_size=max_cache_size, - max_vram_cache_size = self.app_config.max_vram_cache_size, - execution_device = device_type, - precision = precision, - sequential_offload = sequential_offload, - logger = logger, + max_vram_cache_size=self.app_config.max_vram_cache_size, + execution_device=device_type, + precision=precision, + sequential_offload=sequential_offload, + logger=logger, ) self._read_models(config) @@ -348,7 +358,7 @@ class ModelManager(object): self.models = dict() for model_key, model_config in config.items(): - if model_key.startswith('_'): + if model_key.startswith("_"): continue model_name, base_model, model_type = self.parse_key(model_key) model_class = MODEL_CLASSES[base_model][model_type] @@ -391,11 +401,15 @@ class ModelManager(object): base_model: BaseModelType, model_type: ModelType, ) -> str: - return f"{base_model}/{model_type}/{model_name}" + # In 3.11, the behavior of (str,enum) when interpolated into a + # string has changed. The next two lines are defensive. + base_model = BaseModelType(base_model) + model_type = ModelType(model_type) + return f"{base_model.value}/{model_type.value}/{model_name}" @classmethod def parse_key(cls, model_key: str) -> Tuple[str, BaseModelType, ModelType]: - base_model_str, model_type_str, model_name = model_key.split('/', 2) + base_model_str, model_type_str, model_name = model_key.split("/", 2) try: model_type = ModelType(model_type_str) except: @@ -414,20 +428,16 @@ class ModelManager(object): @classmethod def initialize_model_config(cls, config_path: Path): """Create empty config file""" - with open(config_path,'w') as yaml_file: - yaml_file.write(yaml.dump({'__metadata__': - {'version':'3.0.0'} - } - ) - ) + with open(config_path, "w") as yaml_file: + yaml_file.write(yaml.dump({"__metadata__": {"version": "3.0.0"}})) def get_model( self, model_name: str, base_model: BaseModelType, model_type: ModelType, - submodel_type: Optional[SubModelType] = None - )->ModelInfo: + submodel_type: Optional[SubModelType] = None, + ) -> ModelInfo: """Given a model named identified in models.yaml, return an ModelInfo object describing it. :param model_name: symbolic name of the model in models.yaml @@ -451,7 +461,7 @@ class ModelManager(object): if not model_path.exists(): if model_class.save_to_config: self.models[model_key].error = ModelError.NotFound - raise Exception(f"Files for model \"{model_key}\" not found") + raise Exception(f'Files for model "{model_key}" not found') else: self.models.pop(model_key, None) @@ -473,7 +483,7 @@ class ModelManager(object): model_path = model_class.convert_if_required( base_model=base_model, - model_path=str(model_path), # TODO: refactor str/Path types logic + model_path=str(model_path), # TODO: refactor str/Path types logic output_path=dst_convert_path, config=model_config, ) @@ -490,17 +500,17 @@ class ModelManager(object): self.cache_keys[model_key] = set() self.cache_keys[model_key].add(model_context.key) - model_hash = "" # TODO: + model_hash = "" # TODO: return ModelInfo( - context = model_context, - name = model_name, - base_model = base_model, - type = submodel_type or model_type, - hash = model_hash, - location = model_path, # TODO: - precision = self.cache.precision, - _cache = self.cache, + context=model_context, + name=model_name, + base_model=base_model, + type=submodel_type or model_type, + hash=model_hash, + location=model_path, # TODO: + precision=self.cache.precision, + _cache=self.cache, ) def model_info( @@ -516,7 +526,7 @@ class ModelManager(object): if model_key in self.models: return self.models[model_key].dict(exclude_defaults=True) else: - return None # TODO: None or empty dict on not found + return None # TODO: None or empty dict on not found def model_names(self) -> List[Tuple[str, BaseModelType, ModelType]]: """ @@ -526,16 +536,16 @@ class ModelManager(object): return [(self.parse_key(x)) for x in self.models.keys()] def list_model( - self, - model_name: str, - base_model: BaseModelType, - model_type: ModelType, + self, + model_name: str, + base_model: BaseModelType, + model_type: ModelType, ) -> dict: """ Returns a dict describing one installed model, using the combined format of the list_models() method. """ - models = self.list_models(base_model,model_type,model_name) + models = self.list_models(base_model, model_type, model_name) return models[0] if models else None def list_models( @@ -548,13 +558,17 @@ class ModelManager(object): Return a list of models. """ - model_keys = [self.create_key(model_name, base_model, model_type)] if model_name else sorted(self.models, key=str.casefold) + model_keys = ( + [self.create_key(model_name, base_model, model_type)] + if model_name + else sorted(self.models, key=str.casefold) + ) models = [] for model_key in model_keys: model_config = self.models.get(model_key) if not model_config: - self.logger.error(f'Unknown model {model_name}') - raise ModelNotFoundException(f'Unknown model {model_name}') + self.logger.error(f"Unknown model {model_name}") + raise ModelNotFoundException(f"Unknown model {model_name}") cur_model_name, cur_base_model, cur_model_type = self.parse_key(model_key) if base_model is not None and cur_base_model != base_model: @@ -571,8 +585,8 @@ class ModelManager(object): ) # expose paths as absolute to help web UI - if path := model_dict.get('path'): - model_dict['path'] = str(self.app_config.root_path / path) + if path := model_dict.get("path"): + model_dict["path"] = str(self.app_config.root_path / path) models.append(model_dict) return models @@ -641,15 +655,15 @@ class ModelManager(object): model_info(). """ # relativize paths as they go in - this makes it easier to move the root directory around - if path := model_attributes.get('path'): + if path := model_attributes.get("path"): if Path(path).is_relative_to(self.app_config.root_path): - model_attributes['path'] = str(Path(path).relative_to(self.app_config.root_path)) + model_attributes["path"] = str(Path(path).relative_to(self.app_config.root_path)) model_class = MODEL_CLASSES[base_model][model_type] model_config = model_class.create_config(**model_attributes) model_key = self.create_key(model_name, base_model, model_type) - if model_key in self.models and not clobber: + if model_key in self.models and not clobber: raise Exception(f'Attempt to overwrite existing model definition "{model_key}"') old_model = self.models.pop(model_key, None) @@ -675,23 +689,23 @@ class ModelManager(object): self.commit() return AddModelResult( - name = model_name, - model_type = model_type, - base_model = base_model, - config = model_config, + name=model_name, + model_type=model_type, + base_model=base_model, + config=model_config, ) def rename_model( - self, - model_name: str, - base_model: BaseModelType, - model_type: ModelType, - new_name: str = None, - new_base: BaseModelType = None, + self, + model_name: str, + base_model: BaseModelType, + model_type: ModelType, + new_name: str = None, + new_base: BaseModelType = None, ): - ''' + """ Rename or rebase a model. - ''' + """ if new_name is None and new_base is None: self.logger.error("rename_model() called with neither a new_name nor a new_base. {model_name} unchanged.") return @@ -710,7 +724,13 @@ class ModelManager(object): # if this is a model file/directory that we manage ourselves, we need to move it if old_path.is_relative_to(self.app_config.models_path): - new_path = self.app_config.root_path / 'models' / BaseModelType(new_base).value / ModelType(model_type).value / new_name + new_path = ( + self.app_config.root_path + / "models" + / BaseModelType(new_base).value + / ModelType(model_type).value + / new_name + ) move(old_path, new_path) model_cfg.path = str(new_path.relative_to(self.app_config.root_path)) @@ -726,18 +746,18 @@ class ModelManager(object): for cache_id in cache_ids: self.cache.uncache_model(cache_id) - self.models.pop(model_key, None) # delete + self.models.pop(model_key, None) # delete self.models[new_key] = model_cfg self.commit() - def convert_model ( - self, - model_name: str, - base_model: BaseModelType, - model_type: Union[ModelType.Main,ModelType.Vae], - dest_directory: Optional[Path]=None, + def convert_model( + self, + model_name: str, + base_model: BaseModelType, + model_type: Union[ModelType.Main, ModelType.Vae], + dest_directory: Optional[Path] = None, ) -> AddModelResult: - ''' + """ Convert a checkpoint file into a diffusers folder, deleting the cached version and deleting the original checkpoint file if it is in the models directory. @@ -746,7 +766,7 @@ class ModelManager(object): :param model_type: Type of model ['vae' or 'main'] This will raise a ValueError unless the model is a checkpoint. - ''' + """ info = self.model_info(model_name, base_model, model_type) if info["model_format"] != "checkpoint": raise ValueError(f"not a checkpoint format model: {model_name}") @@ -754,27 +774,32 @@ class ModelManager(object): # We are taking advantage of a side effect of get_model() that converts check points # into cached diffusers directories stored at `location`. It doesn't matter # what submodeltype we request here, so we get the smallest. - submodel = {"submodel_type": SubModelType.Tokenizer} if model_type==ModelType.Main else {} - model = self.get_model(model_name, - base_model, - model_type, - **submodel, - ) + submodel = {"submodel_type": SubModelType.Scheduler} if model_type == ModelType.Main else {} + model = self.get_model( + model_name, + base_model, + model_type, + **submodel, + ) checkpoint_path = self.app_config.root_path / info["path"] old_diffusers_path = self.app_config.models_path / model.location - new_diffusers_path = (dest_directory or self.app_config.models_path / base_model.value / model_type.value) / model_name + new_diffusers_path = ( + dest_directory or self.app_config.models_path / base_model.value / model_type.value + ) / model_name if new_diffusers_path.exists(): raise ValueError(f"A diffusers model already exists at {new_diffusers_path}") try: - move(old_diffusers_path,new_diffusers_path) + move(old_diffusers_path, new_diffusers_path) info["model_format"] = "diffusers" - info["path"] = str(new_diffusers_path) if dest_directory else str(new_diffusers_path.relative_to(self.app_config.root_path)) - info.pop('config') + info["path"] = ( + str(new_diffusers_path) + if dest_directory + else str(new_diffusers_path.relative_to(self.app_config.root_path)) + ) + info.pop("config") - result = self.add_model(model_name, base_model, model_type, - model_attributes = info, - clobber=True) + result = self.add_model(model_name, base_model, model_type, model_attributes=info, clobber=True) except: # something went wrong, so don't leave dangling diffusers model in directory or it will cause a duplicate model error! rmtree(new_diffusers_path) @@ -798,15 +823,12 @@ class ModelManager(object): found_models = [] for file in files: location = str(file.resolve()).replace("\\", "/") - if ( - "model.safetensors" not in location - and "diffusion_pytorch_model.safetensors" not in location - ): + if "model.safetensors" not in location and "diffusion_pytorch_model.safetensors" not in location: found_models.append({"name": file.stem, "location": location}) return search_folder, found_models - def commit(self, conf_file: Path=None) -> None: + def commit(self, conf_file: Path = None) -> None: """ Write current configuration out to the indicated file. """ @@ -824,7 +846,7 @@ class ModelManager(object): yaml_str = OmegaConf.to_yaml(data_to_save) config_file_path = conf_file or self.config_path - assert config_file_path is not None,'no config file path to write to' + assert config_file_path is not None, "no config file path to write to" config_file_path = self.app_config.root_path / config_file_path tmpfile = os.path.join(os.path.dirname(config_file_path), "new_config.tmp") try: @@ -857,11 +879,10 @@ class ModelManager(object): base_model: Optional[BaseModelType] = None, model_type: Optional[ModelType] = None, ): - loaded_files = set() new_models_found = False - self.logger.info(f'Scanning {self.app_config.models_path} for new models') + self.logger.info(f"Scanning {self.app_config.models_path} for new models") with Chdir(self.app_config.root_path): for model_key, model_config in list(self.models.items()): model_name, cur_base_model, cur_model_type = self.parse_key(model_key) @@ -887,10 +908,10 @@ class ModelManager(object): models_dir = self.app_config.models_path / cur_base_model.value / cur_model_type.value if not models_dir.exists(): - continue # TODO: or create all folders? + continue # TODO: or create all folders? for model_path in models_dir.iterdir(): - if model_path not in loaded_files: # TODO: check + if model_path not in loaded_files: # TODO: check model_name = model_path.name if model_path.is_dir() else model_path.stem model_key = self.create_key(model_name, cur_base_model, cur_model_type) @@ -900,7 +921,7 @@ class ModelManager(object): if model_path.is_relative_to(self.app_config.root_path): model_path = model_path.relative_to(self.app_config.root_path) - + model_config: ModelConfigBase = model_class.probe_config(str(model_path)) self.models[model_key] = model_config new_models_found = True @@ -916,11 +937,10 @@ class ModelManager(object): if (new_models_found or imported_models) and self.config_path: self.commit() - - def autoimport(self)->Dict[str, AddModelResult]: - ''' + def autoimport(self) -> Dict[str, AddModelResult]: + """ Scan the autoimport directory (if defined) and import new models, delete defunct models. - ''' + """ # avoid circular import from invokeai.backend.install.model_install_backend import ModelInstall from invokeai.frontend.install.model_install import ask_user_for_prediction_type @@ -939,7 +959,9 @@ class ModelManager(object): self.new_models_found.update(self.installer.heuristic_import(model)) def on_search_completed(self): - self.logger.info(f'Scanned {self._items_scanned} files and directories, imported {len(self.new_models_found)} models') + self.logger.info( + f"Scanned {self._items_scanned} files and directories, imported {len(self.new_models_found)} models" + ) def models_found(self): return self.new_models_found @@ -949,31 +971,37 @@ class ModelManager(object): # LS: hacky # Patch in the SD VAE from core so that it is available for use by the UI try: - self.heuristic_import({config.root_path / 'models/core/convert/sd-vae-ft-mse'}) + self.heuristic_import({config.root_path / "models/core/convert/sd-vae-ft-mse"}) except: pass - installer = ModelInstall(config = self.app_config, - model_manager = self, - prediction_type_helper = ask_user_for_prediction_type, - ) - known_paths = {config.root_path / x['path'] for x in self.list_models()} - directories = {config.root_path / x for x in [config.autoimport_dir, - config.lora_dir, - config.embedding_dir, - config.controlnet_dir, - ] if x - } + installer = ModelInstall( + config=self.app_config, + model_manager=self, + prediction_type_helper=ask_user_for_prediction_type, + ) + known_paths = {config.root_path / x["path"] for x in self.list_models()} + directories = { + config.root_path / x + for x in [ + config.autoimport_dir, + config.lora_dir, + config.embedding_dir, + config.controlnet_dir, + ] + if x + } scanner = ScanAndImport(directories, self.logger, ignore=known_paths, installer=installer) scanner.search() - + return scanner.models_found() - def heuristic_import(self, - items_to_import: Set[str], - prediction_type_helper: Callable[[Path],SchedulerPredictionType]=None, - )->Dict[str, AddModelResult]: - '''Import a list of paths, repo_ids or URLs. Returns the set of + def heuristic_import( + self, + items_to_import: Set[str], + prediction_type_helper: Callable[[Path], SchedulerPredictionType] = None, + ) -> Dict[str, AddModelResult]: + """Import a list of paths, repo_ids or URLs. Returns the set of successfully imported items. :param items_to_import: Set of strings corresponding to models to be imported. :param prediction_type_helper: A callback that receives the Path of a Stable Diffusion 2 checkpoint model and returns a SchedulerPredictionType. @@ -992,14 +1020,15 @@ class ModelManager(object): May return the following exceptions: - ModelNotFoundException - one or more of the items to import is not a valid path, repo_id or URL - ValueError - a corresponding model already exists - ''' + """ # avoid circular import here from invokeai.backend.install.model_install_backend import ModelInstall + successfully_installed = dict() - installer = ModelInstall(config = self.app_config, - prediction_type_helper = prediction_type_helper, - model_manager = self) + installer = ModelInstall( + config=self.app_config, prediction_type_helper=prediction_type_helper, model_manager=self + ) for thing in items_to_import: installed = installer.heuristic_import(thing) successfully_installed.update(installed) diff --git a/invokeai/backend/model_management/model_merge.py b/invokeai/backend/model_management/model_merge.py index 6427b9e430..8cf3ce4ad0 100644 --- a/invokeai/backend/model_management/model_merge.py +++ b/invokeai/backend/model_management/model_merge.py @@ -17,23 +17,25 @@ import invokeai.backend.util.logging as logger from ...backend.model_management import ModelManager, ModelType, BaseModelType, ModelVariantType, AddModelResult + class MergeInterpolationMethod(str, Enum): WeightedSum = "weighted_sum" Sigmoid = "sigmoid" InvSigmoid = "inv_sigmoid" AddDifference = "add_difference" + class ModelMerger(object): def __init__(self, manager: ModelManager): self.manager = manager def merge_diffusion_models( - self, - model_paths: List[Path], - alpha: float = 0.5, - interp: MergeInterpolationMethod = None, - force: bool = False, - **kwargs, + self, + model_paths: List[Path], + alpha: float = 0.5, + interp: MergeInterpolationMethod = None, + force: bool = False, + **kwargs, ) -> DiffusionPipeline: """ :param model_paths: up to three models, designated by their local paths or HuggingFace repo_ids @@ -58,24 +60,23 @@ class ModelMerger(object): merged_pipe = pipe.merge( pretrained_model_name_or_path_list=model_paths, alpha=alpha, - interp=interp.value if interp else None, #diffusers API treats None as "weighted sum" + interp=interp.value if interp else None, # diffusers API treats None as "weighted sum" force=force, **kwargs, ) dlogging.set_verbosity(verbosity) return merged_pipe - - def merge_diffusion_models_and_save ( - self, - model_names: List[str], - base_model: Union[BaseModelType,str], - merged_model_name: str, - alpha: float = 0.5, - interp: MergeInterpolationMethod = None, - force: bool = False, - merge_dest_directory: Optional[Path] = None, - **kwargs, + def merge_diffusion_models_and_save( + self, + model_names: List[str], + base_model: Union[BaseModelType, str], + merged_model_name: str, + alpha: float = 0.5, + interp: MergeInterpolationMethod = None, + force: bool = False, + merge_dest_directory: Optional[Path] = None, + **kwargs, ) -> AddModelResult: """ :param models: up to three models, designated by their InvokeAI models.yaml model name @@ -94,39 +95,45 @@ class ModelMerger(object): config = self.manager.app_config base_model = BaseModelType(base_model) vae = None - + for mod in model_names: info = self.manager.list_model(mod, base_model=base_model, model_type=ModelType.Main) - assert info, f"model {mod}, base_model {base_model}, is unknown" - assert info["model_format"] == "diffusers", f"{mod} is not a diffusers model. It must be optimized before merging" - assert info["variant"] == "normal", f"{mod} is a {info['variant']} model, which cannot currently be merged" - assert len(model_names) <= 2 or \ - interp==MergeInterpolationMethod.AddDifference, "When merging three models, only the 'add_difference' merge method is supported" + assert info, f"model {mod}, base_model {base_model}, is unknown" + assert ( + info["model_format"] == "diffusers" + ), f"{mod} is not a diffusers model. It must be optimized before merging" + assert info["variant"] == "normal", f"{mod} is a {info['variant']} model, which cannot currently be merged" + assert ( + len(model_names) <= 2 or interp == MergeInterpolationMethod.AddDifference + ), "When merging three models, only the 'add_difference' merge method is supported" # pick up the first model's vae if mod == model_names[0]: vae = info.get("vae") model_paths.extend([config.root_path / info["path"]]) - merge_method = None if interp == 'weighted_sum' else MergeInterpolationMethod(interp) - logger.debug(f'interp = {interp}, merge_method={merge_method}') - merged_pipe = self.merge_diffusion_models( - model_paths, alpha, merge_method, force, **kwargs + merge_method = None if interp == "weighted_sum" else MergeInterpolationMethod(interp) + logger.debug(f"interp = {interp}, merge_method={merge_method}") + merged_pipe = self.merge_diffusion_models(model_paths, alpha, merge_method, force, **kwargs) + dump_path = ( + Path(merge_dest_directory) + if merge_dest_directory + else config.models_path / base_model.value / ModelType.Main.value ) - dump_path = Path(merge_dest_directory) if merge_dest_directory else config.models_path / base_model.value / ModelType.Main.value dump_path.mkdir(parents=True, exist_ok=True) dump_path = dump_path / merged_model_name merged_pipe.save_pretrained(dump_path, safe_serialization=1) attributes = dict( - path = str(dump_path), - description = f"Merge of models {', '.join(model_names)}", - model_format = "diffusers", - variant = ModelVariantType.Normal.value, - vae = vae, + path=str(dump_path), + description=f"Merge of models {', '.join(model_names)}", + model_format="diffusers", + variant=ModelVariantType.Normal.value, + vae=vae, + ) + return self.manager.add_model( + merged_model_name, + base_model=base_model, + model_type=ModelType.Main, + model_attributes=attributes, + clobber=True, ) - return self.manager.add_model(merged_model_name, - base_model = base_model, - model_type = ModelType.Main, - model_attributes = attributes, - clobber = True - ) diff --git a/invokeai/backend/model_management/model_probe.py b/invokeai/backend/model_management/model_probe.py index f768417506..0e06f9b32d 100644 --- a/invokeai/backend/model_management/model_probe.py +++ b/invokeai/backend/model_management/model_probe.py @@ -10,12 +10,16 @@ from typing import Callable, Literal, Union, Dict, Optional from picklescan.scanner import scan_file_path from .models import ( - BaseModelType, ModelType, ModelVariantType, - SchedulerPredictionType, SilenceWarnings, - InvalidModelException + BaseModelType, + ModelType, + ModelVariantType, + SchedulerPredictionType, + SilenceWarnings, + InvalidModelException, ) from .models.base import read_checkpoint_meta + @dataclass class ModelProbeInfo(object): model_type: ModelType @@ -23,70 +27,74 @@ class ModelProbeInfo(object): variant_type: ModelVariantType prediction_type: SchedulerPredictionType upcast_attention: bool - format: Literal['diffusers','checkpoint', 'lycoris'] + format: Literal["diffusers", "checkpoint", "lycoris"] image_size: int + class ProbeBase(object): - '''forward declaration''' + """forward declaration""" + pass + class ModelProbe(object): - PROBES = { - 'diffusers': { }, - 'checkpoint': { }, + "diffusers": {}, + "checkpoint": {}, } CLASS2TYPE = { - 'StableDiffusionPipeline' : ModelType.Main, - 'StableDiffusionInpaintPipeline' : ModelType.Main, - 'StableDiffusionXLPipeline' : ModelType.Main, - 'StableDiffusionXLImg2ImgPipeline' : ModelType.Main, - 'AutoencoderKL' : ModelType.Vae, - 'ControlNetModel' : ModelType.ControlNet, + "StableDiffusionPipeline": ModelType.Main, + "StableDiffusionInpaintPipeline": ModelType.Main, + "StableDiffusionXLPipeline": ModelType.Main, + "StableDiffusionXLImg2ImgPipeline": ModelType.Main, + "AutoencoderKL": ModelType.Vae, + "ControlNetModel": ModelType.ControlNet, } - + @classmethod - def register_probe(cls, - format: Literal['diffusers','checkpoint'], - model_type: ModelType, - probe_class: ProbeBase): + def register_probe(cls, format: Literal["diffusers", "checkpoint"], model_type: ModelType, probe_class: ProbeBase): cls.PROBES[format][model_type] = probe_class @classmethod - def heuristic_probe(cls, - model: Union[Dict, ModelMixin, Path], - prediction_type_helper: Callable[[Path],SchedulerPredictionType]=None, - )->ModelProbeInfo: - if isinstance(model,Path): - return cls.probe(model_path=model,prediction_type_helper=prediction_type_helper) - elif isinstance(model,(dict,ModelMixin,ConfigMixin)): + def heuristic_probe( + cls, + model: Union[Dict, ModelMixin, Path], + prediction_type_helper: Callable[[Path], SchedulerPredictionType] = None, + ) -> ModelProbeInfo: + if isinstance(model, Path): + return cls.probe(model_path=model, prediction_type_helper=prediction_type_helper) + elif isinstance(model, (dict, ModelMixin, ConfigMixin)): return cls.probe(model_path=None, model=model, prediction_type_helper=prediction_type_helper) else: raise InvalidModelException("model parameter {model} is neither a Path, nor a model") @classmethod - def probe(cls, - model_path: Path, - model: Optional[Union[Dict, ModelMixin]] = None, - prediction_type_helper: Optional[Callable[[Path],SchedulerPredictionType]] = None)->ModelProbeInfo: - ''' + def probe( + cls, + model_path: Path, + model: Optional[Union[Dict, ModelMixin]] = None, + prediction_type_helper: Optional[Callable[[Path], SchedulerPredictionType]] = None, + ) -> ModelProbeInfo: + """ Probe the model at model_path and return sufficient information about it to place it somewhere in the models directory hierarchy. If the model is already loaded into memory, you may provide it as model in order to avoid opening it a second time. The prediction_type_helper callable is a function that receives the path to the model and returns the BaseModelType. It is called to distinguish between V2-Base and V2-768 SD models. - ''' + """ if model_path: - format_type = 'diffusers' if model_path.is_dir() else 'checkpoint' + format_type = "diffusers" if model_path.is_dir() else "checkpoint" else: - format_type = 'diffusers' if isinstance(model,(ConfigMixin,ModelMixin)) else 'checkpoint' + format_type = "diffusers" if isinstance(model, (ConfigMixin, ModelMixin)) else "checkpoint" model_info = None try: - model_type = cls.get_model_type_from_folder(model_path, model) \ - if format_type == 'diffusers' \ - else cls.get_model_type_from_checkpoint(model_path, model) + model_type = ( + cls.get_model_type_from_folder(model_path, model) + if format_type == "diffusers" + else cls.get_model_type_from_checkpoint(model_path, model) + ) probe_class = cls.PROBES[format_type].get(model_type) if not probe_class: return None @@ -96,17 +104,23 @@ class ModelProbe(object): prediction_type = probe.get_scheduler_prediction_type() format = probe.get_format() model_info = ModelProbeInfo( - model_type = model_type, - base_type = base_type, - variant_type = variant_type, - prediction_type = prediction_type, - upcast_attention = (base_type==BaseModelType.StableDiffusion2 \ - and prediction_type==SchedulerPredictionType.VPrediction), - format = format, - image_size = 1024 if (base_type in {BaseModelType.StableDiffusionXL,BaseModelType.StableDiffusionXLRefiner}) else \ - 768 if (base_type==BaseModelType.StableDiffusion2 \ - and prediction_type==SchedulerPredictionType.VPrediction ) else \ - 512 + model_type=model_type, + base_type=base_type, + variant_type=variant_type, + prediction_type=prediction_type, + upcast_attention=( + base_type == BaseModelType.StableDiffusion2 + and prediction_type == SchedulerPredictionType.VPrediction + ), + format=format, + image_size=1024 + if (base_type in {BaseModelType.StableDiffusionXL, BaseModelType.StableDiffusionXLRefiner}) + else 768 + if ( + base_type == BaseModelType.StableDiffusion2 + and prediction_type == SchedulerPredictionType.VPrediction + ) + else 512, ) except Exception: raise @@ -115,7 +129,7 @@ class ModelProbe(object): @classmethod def get_model_type_from_checkpoint(cls, model_path: Path, checkpoint: dict) -> ModelType: - if model_path.suffix not in ('.bin','.pt','.ckpt','.safetensors','.pth'): + if model_path.suffix not in (".bin", ".pt", ".ckpt", ".safetensors", ".pth"): return None if model_path.name == "learned_embeds.bin": @@ -142,32 +156,32 @@ class ModelProbe(object): # diffusers-ti if len(ckpt) < 10 and all(isinstance(v, torch.Tensor) for v in ckpt.values()): return ModelType.TextualInversion - + raise InvalidModelException(f"Unable to determine model type for {model_path}") @classmethod - def get_model_type_from_folder(cls, folder_path: Path, model: ModelMixin)->ModelType: - ''' + def get_model_type_from_folder(cls, folder_path: Path, model: ModelMixin) -> ModelType: + """ Get the model type of a hugging-face style folder. - ''' + """ class_name = None if model: class_name = model.__class__.__name__ else: - if (folder_path / 'learned_embeds.bin').exists(): + if (folder_path / "learned_embeds.bin").exists(): return ModelType.TextualInversion - if (folder_path / 'pytorch_lora_weights.bin').exists(): + if (folder_path / "pytorch_lora_weights.bin").exists(): return ModelType.Lora - i = folder_path / 'model_index.json' - c = folder_path / 'config.json' + i = folder_path / "model_index.json" + c = folder_path / "config.json" config_path = i if i.exists() else c if c.exists() else None if config_path: - with open(config_path,'r') as file: + with open(config_path, "r") as file: conf = json.load(file) - class_name = conf['_class_name'] + class_name = conf["_class_name"] if class_name and (type := cls.CLASS2TYPE.get(class_name)): return type @@ -176,7 +190,7 @@ class ModelProbe(object): raise InvalidModelException(f"Unable to determine model type for {folder_path}") @classmethod - def _scan_and_load_checkpoint(cls,model_path: Path)->dict: + def _scan_and_load_checkpoint(cls, model_path: Path) -> dict: with SilenceWarnings(): if model_path.suffix.endswith((".ckpt", ".pt", ".bin")): cls._scan_model(model_path, model_path) @@ -186,55 +200,53 @@ class ModelProbe(object): @classmethod def _scan_model(cls, model_name, checkpoint): - """ - Apply picklescanner to the indicated checkpoint and issue a warning - and option to exit if an infected file is identified. - """ - # scan model - scan_result = scan_file_path(checkpoint) - if scan_result.infected_files != 0: - raise "The model {model_name} is potentially infected by malware. Aborting import." + """ + Apply picklescanner to the indicated checkpoint and issue a warning + and option to exit if an infected file is identified. + """ + # scan model + scan_result = scan_file_path(checkpoint) + if scan_result.infected_files != 0: + raise "The model {model_name} is potentially infected by malware. Aborting import." + ###################################################3 # Checkpoint probing ###################################################3 class ProbeBase(object): - def get_base_type(self)->BaseModelType: + def get_base_type(self) -> BaseModelType: pass - def get_variant_type(self)->ModelVariantType: - pass - - def get_scheduler_prediction_type(self)->SchedulerPredictionType: + def get_variant_type(self) -> ModelVariantType: pass - def get_format(self)->str: + def get_scheduler_prediction_type(self) -> SchedulerPredictionType: pass + def get_format(self) -> str: + pass + + class CheckpointProbeBase(ProbeBase): - def __init__(self, - checkpoint_path: Path, - checkpoint: dict, - helper: Callable[[Path],SchedulerPredictionType] = None - )->BaseModelType: + def __init__( + self, checkpoint_path: Path, checkpoint: dict, helper: Callable[[Path], SchedulerPredictionType] = None + ) -> BaseModelType: self.checkpoint = checkpoint or ModelProbe._scan_and_load_checkpoint(checkpoint_path) self.checkpoint_path = checkpoint_path self.helper = helper - def get_base_type(self)->BaseModelType: + def get_base_type(self) -> BaseModelType: pass - def get_format(self)->str: - return 'checkpoint' + def get_format(self) -> str: + return "checkpoint" - def get_variant_type(self)-> ModelVariantType: - model_type = ModelProbe.get_model_type_from_checkpoint(self.checkpoint_path,self.checkpoint) + def get_variant_type(self) -> ModelVariantType: + model_type = ModelProbe.get_model_type_from_checkpoint(self.checkpoint_path, self.checkpoint) if model_type != ModelType.Main: return ModelVariantType.Normal - state_dict = self.checkpoint.get('state_dict') or self.checkpoint - in_channels = state_dict[ - "model.diffusion_model.input_blocks.0.0.weight" - ].shape[1] + state_dict = self.checkpoint.get("state_dict") or self.checkpoint + in_channels = state_dict["model.diffusion_model.input_blocks.0.0.weight"].shape[1] if in_channels == 9: return ModelVariantType.Inpaint elif in_channels == 5: @@ -242,18 +254,21 @@ class CheckpointProbeBase(ProbeBase): elif in_channels == 4: return ModelVariantType.Normal else: - raise InvalidModelException(f"Cannot determine variant type (in_channels={in_channels}) at {self.checkpoint_path}") + raise InvalidModelException( + f"Cannot determine variant type (in_channels={in_channels}) at {self.checkpoint_path}" + ) + class PipelineCheckpointProbe(CheckpointProbeBase): - def get_base_type(self)->BaseModelType: + def get_base_type(self) -> BaseModelType: checkpoint = self.checkpoint - state_dict = self.checkpoint.get('state_dict') or checkpoint + state_dict = self.checkpoint.get("state_dict") or checkpoint key_name = "model.diffusion_model.input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight" if key_name in state_dict and state_dict[key_name].shape[-1] == 768: return BaseModelType.StableDiffusion1 if key_name in state_dict and state_dict[key_name].shape[-1] == 1024: return BaseModelType.StableDiffusion2 - key_name = 'model.diffusion_model.input_blocks.4.1.transformer_blocks.0.attn2.to_k.weight' + key_name = "model.diffusion_model.input_blocks.4.1.transformer_blocks.0.attn2.to_k.weight" if key_name in state_dict and state_dict[key_name].shape[-1] == 2048: return BaseModelType.StableDiffusionXL elif key_name in state_dict and state_dict[key_name].shape[-1] == 1280: @@ -261,35 +276,38 @@ class PipelineCheckpointProbe(CheckpointProbeBase): else: raise InvalidModelException("Cannot determine base type") - def get_scheduler_prediction_type(self)->SchedulerPredictionType: + def get_scheduler_prediction_type(self) -> SchedulerPredictionType: type = self.get_base_type() if type == BaseModelType.StableDiffusion1: return SchedulerPredictionType.Epsilon checkpoint = self.checkpoint - state_dict = self.checkpoint.get('state_dict') or checkpoint + state_dict = self.checkpoint.get("state_dict") or checkpoint key_name = "model.diffusion_model.input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight" if key_name in state_dict and state_dict[key_name].shape[-1] == 1024: - if 'global_step' in checkpoint: - if checkpoint['global_step'] == 220000: + if "global_step" in checkpoint: + if checkpoint["global_step"] == 220000: return SchedulerPredictionType.Epsilon elif checkpoint["global_step"] == 110000: return SchedulerPredictionType.VPrediction - if self.checkpoint_path and self.helper \ - and not self.checkpoint_path.with_suffix('.yaml').exists(): # if a .yaml config file exists, then this step not needed + if ( + self.checkpoint_path and self.helper and not self.checkpoint_path.with_suffix(".yaml").exists() + ): # if a .yaml config file exists, then this step not needed return self.helper(self.checkpoint_path) else: return None + class VaeCheckpointProbe(CheckpointProbeBase): - def get_base_type(self)->BaseModelType: + def get_base_type(self) -> BaseModelType: # I can't find any standalone 2.X VAEs to test with! return BaseModelType.StableDiffusion1 -class LoRACheckpointProbe(CheckpointProbeBase): - def get_format(self)->str: - return 'lycoris' - def get_base_type(self)->BaseModelType: +class LoRACheckpointProbe(CheckpointProbeBase): + def get_format(self) -> str: + return "lycoris" + + def get_base_type(self) -> BaseModelType: checkpoint = self.checkpoint key1 = "lora_te_text_model_encoder_layers_0_mlp_fc1.lora_down.weight" key2 = "lora_te_text_model_encoder_layers_0_self_attn_k_proj.hada_w1_a" @@ -307,16 +325,17 @@ class LoRACheckpointProbe(CheckpointProbeBase): else: return None + class TextualInversionCheckpointProbe(CheckpointProbeBase): - def get_format(self)->str: + def get_format(self) -> str: return None - def get_base_type(self)->BaseModelType: + def get_base_type(self) -> BaseModelType: checkpoint = self.checkpoint - if 'string_to_token' in checkpoint: - token_dim = list(checkpoint['string_to_param'].values())[0].shape[-1] - elif 'emb_params' in checkpoint: - token_dim = checkpoint['emb_params'].shape[-1] + if "string_to_token" in checkpoint: + token_dim = list(checkpoint["string_to_param"].values())[0].shape[-1] + elif "emb_params" in checkpoint: + token_dim = checkpoint["emb_params"].shape[-1] else: token_dim = list(checkpoint.values())[0].shape[0] if token_dim == 768: @@ -326,12 +345,14 @@ class TextualInversionCheckpointProbe(CheckpointProbeBase): else: return None + class ControlNetCheckpointProbe(CheckpointProbeBase): - def get_base_type(self)->BaseModelType: + def get_base_type(self) -> BaseModelType: checkpoint = self.checkpoint - for key_name in ('control_model.input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight', - 'input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight' - ): + for key_name in ( + "control_model.input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight", + "input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight", + ): if key_name not in checkpoint: continue if checkpoint[key_name].shape[-1] == 768: @@ -342,56 +363,54 @@ class ControlNetCheckpointProbe(CheckpointProbeBase): return self.helper(self.checkpoint_path) raise InvalidModelException("Unable to determine base type for {self.checkpoint_path}") + ######################################################## # classes for probing folders ####################################################### class FolderProbeBase(ProbeBase): - def __init__(self, - folder_path: Path, - model: ModelMixin = None, - helper: Callable=None # not used - ): + def __init__(self, folder_path: Path, model: ModelMixin = None, helper: Callable = None): # not used self.model = model self.folder_path = folder_path - def get_variant_type(self)->ModelVariantType: + def get_variant_type(self) -> ModelVariantType: return ModelVariantType.Normal - def get_format(self)->str: - return 'diffusers' - + def get_format(self) -> str: + return "diffusers" + + class PipelineFolderProbe(FolderProbeBase): - def get_base_type(self)->BaseModelType: + def get_base_type(self) -> BaseModelType: if self.model: unet_conf = self.model.unet.config else: - with open(self.folder_path / 'unet' / 'config.json','r') as file: + with open(self.folder_path / "unet" / "config.json", "r") as file: unet_conf = json.load(file) - if unet_conf['cross_attention_dim'] == 768: - return BaseModelType.StableDiffusion1 - elif unet_conf['cross_attention_dim'] == 1024: + if unet_conf["cross_attention_dim"] == 768: + return BaseModelType.StableDiffusion1 + elif unet_conf["cross_attention_dim"] == 1024: return BaseModelType.StableDiffusion2 - elif unet_conf['cross_attention_dim'] == 1280: + elif unet_conf["cross_attention_dim"] == 1280: return BaseModelType.StableDiffusionXLRefiner - elif unet_conf['cross_attention_dim'] == 2048: + elif unet_conf["cross_attention_dim"] == 2048: return BaseModelType.StableDiffusionXL else: - raise InvalidModelException(f'Unknown base model for {self.folder_path}') + raise InvalidModelException(f"Unknown base model for {self.folder_path}") - def get_scheduler_prediction_type(self)->SchedulerPredictionType: + def get_scheduler_prediction_type(self) -> SchedulerPredictionType: if self.model: scheduler_conf = self.model.scheduler.config else: - with open(self.folder_path / 'scheduler' / 'scheduler_config.json','r') as file: + with open(self.folder_path / "scheduler" / "scheduler_config.json", "r") as file: scheduler_conf = json.load(file) - if scheduler_conf['prediction_type'] == "v_prediction": + if scheduler_conf["prediction_type"] == "v_prediction": return SchedulerPredictionType.VPrediction - elif scheduler_conf['prediction_type'] == 'epsilon': + elif scheduler_conf["prediction_type"] == "epsilon": return SchedulerPredictionType.Epsilon else: return None - - def get_variant_type(self)->ModelVariantType: + + def get_variant_type(self) -> ModelVariantType: # This only works for pipelines! Any kind of # exception results in our returning the # "normal" variant type @@ -399,11 +418,11 @@ class PipelineFolderProbe(FolderProbeBase): if self.model: conf = self.model.unet.config else: - config_file = self.folder_path / 'unet' / 'config.json' - with open(config_file,'r') as file: + config_file = self.folder_path / "unet" / "config.json" + with open(config_file, "r") as file: conf = json.load(file) - - in_channels = conf['in_channels'] + + in_channels = conf["in_channels"] if in_channels == 9: return ModelVariantType.Inpaint elif in_channels == 5: @@ -414,53 +433,67 @@ class PipelineFolderProbe(FolderProbeBase): pass return ModelVariantType.Normal + class VaeFolderProbe(FolderProbeBase): - def get_base_type(self)->BaseModelType: - return BaseModelType.StableDiffusion1 + def get_base_type(self) -> BaseModelType: + config_file = self.folder_path / "config.json" + if not config_file.exists(): + raise InvalidModelException(f"Cannot determine base type for {self.folder_path}") + with open(config_file, "r") as file: + config = json.load(file) + return ( + BaseModelType.StableDiffusionXL + if config.get("scaling_factor", 0) == 0.13025 and config.get("sample_size") in [512, 1024] + else BaseModelType.StableDiffusion1 + ) + class TextualInversionFolderProbe(FolderProbeBase): - def get_format(self)->str: + def get_format(self) -> str: return None - - def get_base_type(self)->BaseModelType: - path = self.folder_path / 'learned_embeds.bin' + + def get_base_type(self) -> BaseModelType: + path = self.folder_path / "learned_embeds.bin" if not path.exists(): return None checkpoint = ModelProbe._scan_and_load_checkpoint(path) - return TextualInversionCheckpointProbe(None,checkpoint=checkpoint).get_base_type() + return TextualInversionCheckpointProbe(None, checkpoint=checkpoint).get_base_type() + class ControlNetFolderProbe(FolderProbeBase): - def get_base_type(self)->BaseModelType: - config_file = self.folder_path / 'config.json' + def get_base_type(self) -> BaseModelType: + config_file = self.folder_path / "config.json" if not config_file.exists(): raise InvalidModelException(f"Cannot determine base type for {self.folder_path}") - with open(config_file,'r') as file: + with open(config_file, "r") as file: config = json.load(file) # no obvious way to distinguish between sd2-base and sd2-768 - return BaseModelType.StableDiffusion1 \ - if config['cross_attention_dim']==768 \ - else BaseModelType.StableDiffusion2 + return ( + BaseModelType.StableDiffusion1 if config["cross_attention_dim"] == 768 else BaseModelType.StableDiffusion2 + ) + class LoRAFolderProbe(FolderProbeBase): - def get_base_type(self)->BaseModelType: + def get_base_type(self) -> BaseModelType: model_file = None - for suffix in ['safetensors','bin']: - base_file = self.folder_path / f'pytorch_lora_weights.{suffix}' + for suffix in ["safetensors", "bin"]: + base_file = self.folder_path / f"pytorch_lora_weights.{suffix}" if base_file.exists(): model_file = base_file break if not model_file: - raise InvalidModelException('Unknown LoRA format encountered') - return LoRACheckpointProbe(model_file,None).get_base_type() + raise InvalidModelException("Unknown LoRA format encountered") + return LoRACheckpointProbe(model_file, None).get_base_type() + ############## register probe classes ###### -ModelProbe.register_probe('diffusers', ModelType.Main, PipelineFolderProbe) -ModelProbe.register_probe('diffusers', ModelType.Vae, VaeFolderProbe) -ModelProbe.register_probe('diffusers', ModelType.Lora, LoRAFolderProbe) -ModelProbe.register_probe('diffusers', ModelType.TextualInversion, TextualInversionFolderProbe) -ModelProbe.register_probe('diffusers', ModelType.ControlNet, ControlNetFolderProbe) -ModelProbe.register_probe('checkpoint', ModelType.Main, PipelineCheckpointProbe) -ModelProbe.register_probe('checkpoint', ModelType.Vae, VaeCheckpointProbe) -ModelProbe.register_probe('checkpoint', ModelType.Lora, LoRACheckpointProbe) -ModelProbe.register_probe('checkpoint', ModelType.TextualInversion, TextualInversionCheckpointProbe) -ModelProbe.register_probe('checkpoint', ModelType.ControlNet, ControlNetCheckpointProbe) +ModelProbe.register_probe("diffusers", ModelType.Main, PipelineFolderProbe) +ModelProbe.register_probe("diffusers", ModelType.Vae, VaeFolderProbe) +ModelProbe.register_probe("diffusers", ModelType.Lora, LoRAFolderProbe) +ModelProbe.register_probe("diffusers", ModelType.TextualInversion, TextualInversionFolderProbe) +ModelProbe.register_probe("diffusers", ModelType.ControlNet, ControlNetFolderProbe) +ModelProbe.register_probe("checkpoint", ModelType.Main, PipelineCheckpointProbe) +ModelProbe.register_probe("checkpoint", ModelType.Vae, VaeCheckpointProbe) +ModelProbe.register_probe("checkpoint", ModelType.Lora, LoRACheckpointProbe) +ModelProbe.register_probe("checkpoint", ModelType.TextualInversion, TextualInversionCheckpointProbe) +ModelProbe.register_probe("checkpoint", ModelType.ControlNet, ControlNetCheckpointProbe) diff --git a/invokeai/backend/model_management/model_search.py b/invokeai/backend/model_management/model_search.py index 5657bd9549..9c87d6c408 100644 --- a/invokeai/backend/model_management/model_search.py +++ b/invokeai/backend/model_management/model_search.py @@ -10,8 +10,9 @@ from pathlib import Path import invokeai.backend.util.logging as logger + class ModelSearch(ABC): - def __init__(self, directories: List[Path], logger: types.ModuleType=logger): + def __init__(self, directories: List[Path], logger: types.ModuleType = logger): """ Initialize a recursive model directory search. :param directories: List of directory Paths to recurse through @@ -56,18 +57,23 @@ class ModelSearch(ABC): def walk_directory(self, path: Path): for root, dirs, files in os.walk(path): - if str(Path(root).name).startswith('.'): + if str(Path(root).name).startswith("."): self._pruned_paths.add(root) if any([Path(root).is_relative_to(x) for x in self._pruned_paths]): continue - + self._items_scanned += len(dirs) + len(files) for d in dirs: path = Path(root) / d if path in self._scanned_paths or path.parent in self._scanned_dirs: self._scanned_dirs.add(path) continue - if any([(path/x).exists() for x in {'config.json','model_index.json','learned_embeds.bin','pytorch_lora_weights.bin'}]): + if any( + [ + (path / x).exists() + for x in {"config.json", "model_index.json", "learned_embeds.bin", "pytorch_lora_weights.bin"} + ] + ): try: self.on_model_found(path) self._models_found += 1 @@ -79,18 +85,19 @@ class ModelSearch(ABC): path = Path(root) / f if path.parent in self._scanned_dirs: continue - if path.suffix in {'.ckpt','.bin','.pth','.safetensors','.pt'}: + if path.suffix in {".ckpt", ".bin", ".pth", ".safetensors", ".pt"}: try: self.on_model_found(path) self._models_found += 1 except Exception as e: self.logger.warning(str(e)) + class FindModels(ModelSearch): def on_search_started(self): self.models_found: Set[Path] = set() - def on_model_found(self,model: Path): + def on_model_found(self, model: Path): self.models_found.add(model) def on_search_completed(self): @@ -99,5 +106,3 @@ class FindModels(ModelSearch): def list_models(self) -> List[Path]: self.search() return list(self.models_found) - - diff --git a/invokeai/backend/model_management/models/__init__.py b/invokeai/backend/model_management/models/__init__.py index 2eb9028d6e..b15e1d309a 100644 --- a/invokeai/backend/model_management/models/__init__.py +++ b/invokeai/backend/model_management/models/__init__.py @@ -3,15 +3,24 @@ from enum import Enum from pydantic import BaseModel from typing import Literal, get_origin from .base import ( - BaseModelType, ModelType, SubModelType, ModelBase, ModelConfigBase, - ModelVariantType, SchedulerPredictionType, ModelError, SilenceWarnings, - ModelNotFoundException, InvalidModelException, DuplicateModelException - ) + BaseModelType, + ModelType, + SubModelType, + ModelBase, + ModelConfigBase, + ModelVariantType, + SchedulerPredictionType, + ModelError, + SilenceWarnings, + ModelNotFoundException, + InvalidModelException, + DuplicateModelException, +) from .stable_diffusion import StableDiffusion1Model, StableDiffusion2Model from .sdxl import StableDiffusionXLModel from .vae import VaeModel from .lora import LoRAModel -from .controlnet import ControlNetModel # TODO: +from .controlnet import ControlNetModel # TODO: from .textual_inversion import TextualInversionModel MODEL_CLASSES = { @@ -45,18 +54,19 @@ MODEL_CLASSES = { ModelType.ControlNet: ControlNetModel, ModelType.TextualInversion: TextualInversionModel, }, - #BaseModelType.Kandinsky2_1: { + # BaseModelType.Kandinsky2_1: { # ModelType.Main: Kandinsky2_1Model, # ModelType.MoVQ: MoVQModel, # ModelType.Lora: LoRAModel, # ModelType.ControlNet: ControlNetModel, # ModelType.TextualInversion: TextualInversionModel, - #}, + # }, } MODEL_CONFIGS = list() OPENAPI_MODEL_CONFIGS = list() + class OpenAPIModelInfoBase(BaseModel): model_name: str base_model: BaseModelType @@ -72,27 +82,31 @@ for base_model, models in MODEL_CLASSES.items(): # LS: sort to get the checkpoint configs first, which makes # for a better template in the Swagger docs for cfg in sorted(model_configs, key=lambda x: str(x)): - model_name, cfg_name = cfg.__qualname__.split('.')[-2:] + model_name, cfg_name = cfg.__qualname__.split(".")[-2:] openapi_cfg_name = model_name + cfg_name if openapi_cfg_name in vars(): continue - api_wrapper = type(openapi_cfg_name, (cfg, OpenAPIModelInfoBase), dict( - __annotations__ = dict( - model_type=Literal[model_type.value], + api_wrapper = type( + openapi_cfg_name, + (cfg, OpenAPIModelInfoBase), + dict( + __annotations__=dict( + model_type=Literal[model_type.value], + ), ), - )) + ) - #globals()[openapi_cfg_name] = api_wrapper + # globals()[openapi_cfg_name] = api_wrapper vars()[openapi_cfg_name] = api_wrapper OPENAPI_MODEL_CONFIGS.append(api_wrapper) + def get_model_config_enums(): enums = list() for model_config in MODEL_CONFIGS: - - if hasattr(inspect,'get_annotations'): + if hasattr(inspect, "get_annotations"): fields = inspect.get_annotations(model_config) else: fields = model_config.__annotations__ @@ -109,7 +123,9 @@ def get_model_config_enums(): if isinstance(field, type) and issubclass(field, str) and issubclass(field, Enum): enums.append(field) - elif get_origin(field) is Literal and all(isinstance(arg, str) and isinstance(arg, Enum) for arg in field.__args__): + elif get_origin(field) is Literal and all( + isinstance(arg, str) and isinstance(arg, Enum) for arg in field.__args__ + ): enums.append(type(field.__args__[0])) elif field is None: @@ -119,4 +135,3 @@ def get_model_config_enums(): raise Exception(f"Unsupported format definition in {model_configs.__qualname__}") return enums - diff --git a/invokeai/backend/model_management/models/base.py b/invokeai/backend/model_management/models/base.py index 912c3270cd..f2142f772f 100644 --- a/invokeai/backend/model_management/models/base.py +++ b/invokeai/backend/model_management/models/base.py @@ -15,29 +15,35 @@ from contextlib import suppress from pydantic import BaseModel, Field from typing import List, Dict, Optional, Type, Literal, TypeVar, Generic, Callable, Any, Union + class DuplicateModelException(Exception): pass + class InvalidModelException(Exception): pass + class ModelNotFoundException(Exception): pass + class BaseModelType(str, Enum): StableDiffusion1 = "sd-1" StableDiffusion2 = "sd-2" StableDiffusionXL = "sdxl" StableDiffusionXLRefiner = "sdxl-refiner" - #Kandinsky2_1 = "kandinsky-2.1" + # Kandinsky2_1 = "kandinsky-2.1" + class ModelType(str, Enum): Main = "main" Vae = "vae" Lora = "lora" - ControlNet = "controlnet" # used by model_probe + ControlNet = "controlnet" # used by model_probe TextualInversion = "embedding" + class SubModelType(str, Enum): UNet = "unet" TextEncoder = "text_encoder" @@ -47,23 +53,27 @@ class SubModelType(str, Enum): Vae = "vae" Scheduler = "scheduler" SafetyChecker = "safety_checker" - #MoVQ = "movq" + # MoVQ = "movq" + class ModelVariantType(str, Enum): Normal = "normal" Inpaint = "inpaint" Depth = "depth" + class SchedulerPredictionType(str, Enum): Epsilon = "epsilon" VPrediction = "v_prediction" Sample = "sample" - + + class ModelError(str, Enum): NotFound = "not_found" + class ModelConfigBase(BaseModel): - path: str # or Path + path: str # or Path description: Optional[str] = Field(None) model_format: Optional[str] = Field(None) error: Optional[ModelError] = Field(None) @@ -71,13 +81,17 @@ class ModelConfigBase(BaseModel): class Config: use_enum_values = True + class EmptyConfigLoader(ConfigMixin): @classmethod def load_config(cls, *args, **kwargs): cls.config_name = kwargs.pop("config_name") return super().load_config(*args, **kwargs) -T_co = TypeVar('T_co', covariant=True) + +T_co = TypeVar("T_co", covariant=True) + + class classproperty(Generic[T_co]): def __init__(self, fget: Callable[[Any], T_co]) -> None: self.fget = fget @@ -86,12 +100,13 @@ class classproperty(Generic[T_co]): return self.fget(owner) def __set__(self, instance: Optional[Any], value: Any) -> None: - raise AttributeError('cannot set attribute') + raise AttributeError("cannot set attribute") + class ModelBase(metaclass=ABCMeta): - #model_path: str - #base_model: BaseModelType - #model_type: ModelType + # model_path: str + # base_model: BaseModelType + # model_type: ModelType def __init__( self, @@ -110,7 +125,7 @@ class ModelBase(metaclass=ABCMeta): return None elif any(t is None for t in subtypes): raise Exception(f"Unsupported definition: {subtypes}") - + if subtypes[0] in ["diffusers", "transformers"]: res_type = sys.modules[subtypes[0]] subtypes = subtypes[1:] @@ -119,7 +134,6 @@ class ModelBase(metaclass=ABCMeta): res_type = sys.modules["diffusers"] res_type = getattr(res_type, "pipelines") - for subtype in subtypes: res_type = getattr(res_type, subtype) return res_type @@ -128,7 +142,7 @@ class ModelBase(metaclass=ABCMeta): def _get_configs(cls): with suppress(Exception): return cls.__configs - + configs = dict() for name in dir(cls): if name.startswith("__"): @@ -138,7 +152,7 @@ class ModelBase(metaclass=ABCMeta): if not isinstance(value, type) or not issubclass(value, ModelConfigBase): continue - if hasattr(inspect,'get_annotations'): + if hasattr(inspect, "get_annotations"): fields = inspect.get_annotations(value) else: fields = value.__annotations__ @@ -151,7 +165,9 @@ class ModelBase(metaclass=ABCMeta): for model_format in field: configs[model_format.value] = value - elif typing.get_origin(field) is Literal and all(isinstance(arg, str) and isinstance(arg, Enum) for arg in field.__args__): + elif typing.get_origin(field) is Literal and all( + isinstance(arg, str) and isinstance(arg, Enum) for arg in field.__args__ + ): for model_format in field.__args__: configs[model_format.value] = value @@ -203,8 +219,8 @@ class ModelBase(metaclass=ABCMeta): class DiffusersModel(ModelBase): - #child_types: Dict[str, Type] - #child_sizes: Dict[str, int] + # child_types: Dict[str, Type] + # child_sizes: Dict[str, int] def __init__(self, model_path: str, base_model: BaseModelType, model_type: ModelType): super().__init__(model_path, base_model, model_type) @@ -214,7 +230,7 @@ class DiffusersModel(ModelBase): try: config_data = DiffusionPipeline.load_config(self.model_path) - #config_data = json.loads(os.path.join(self.model_path, "model_index.json")) + # config_data = json.loads(os.path.join(self.model_path, "model_index.json")) except: raise Exception("Invalid diffusers model! (model_index.json not found or invalid)") @@ -228,14 +244,12 @@ class DiffusersModel(ModelBase): self.child_types[child_name] = child_type self.child_sizes[child_name] = calc_model_size_by_fs(self.model_path, subfolder=child_name) - def get_size(self, child_type: Optional[SubModelType] = None): if child_type is None: return sum(self.child_sizes.values()) else: return self.child_sizes[child_type] - def get_model( self, torch_dtype: Optional[torch.dtype], @@ -245,7 +259,7 @@ class DiffusersModel(ModelBase): if child_type is None: raise Exception("Child model type can't be null on diffusers model") if child_type not in self.child_types: - return None # TODO: or raise + return None # TODO: or raise if torch_dtype == torch.float16: variants = ["fp16", None] @@ -265,8 +279,8 @@ class DiffusersModel(ModelBase): ) break except Exception as e: - #print("====ERR LOAD====") - #print(f"{variant}: {e}") + # print("====ERR LOAD====") + # print(f"{variant}: {e}") pass else: raise Exception(f"Failed to load {self.base_model}:{self.model_type}:{child_type} model") @@ -275,15 +289,10 @@ class DiffusersModel(ModelBase): self.child_sizes[child_type] = calc_model_size_by_data(model) return model - #def convert_if_required(model_path: str, cache_path: str, config: Optional[dict]) -> str: + # def convert_if_required(model_path: str, cache_path: str, config: Optional[dict]) -> str: - -def calc_model_size_by_fs( - model_path: str, - subfolder: Optional[str] = None, - variant: Optional[str] = None -): +def calc_model_size_by_fs(model_path: str, subfolder: Optional[str] = None, variant: Optional[str] = None): if subfolder is not None: model_path = os.path.join(model_path, subfolder) @@ -325,12 +334,12 @@ def calc_model_size_by_fs( # calculate files size if there is no index file formats = [ - (".safetensors",), # safetensors - (".bin",), # torch - (".onnx", ".pb"), # onnx - (".msgpack",), # flax - (".ckpt",), # tf - (".h5",), # tf2 + (".safetensors",), # safetensors + (".bin",), # torch + (".onnx", ".pb"), # onnx + (".msgpack",), # flax + (".ckpt",), # tf + (".h5",), # tf2 ] for file_format in formats: @@ -343,9 +352,9 @@ def calc_model_size_by_fs( file_stats = os.stat(os.path.join(model_path, model_file)) model_size += file_stats.st_size return model_size - - #raise NotImplementedError(f"Unknown model structure! Files: {all_files}") - return 0 # scheduler/feature_extractor/tokenizer - models without loading to gpu + + # raise NotImplementedError(f"Unknown model structure! Files: {all_files}") + return 0 # scheduler/feature_extractor/tokenizer - models without loading to gpu def calc_model_size_by_data(model) -> int: @@ -364,12 +373,12 @@ def _calc_pipeline_by_data(pipeline) -> int: if submodel is not None and isinstance(submodel, torch.nn.Module): res += _calc_model_by_data(submodel) return res - + def _calc_model_by_data(model) -> int: - mem_params = sum([param.nelement()*param.element_size() for param in model.parameters()]) - mem_bufs = sum([buf.nelement()*buf.element_size() for buf in model.buffers()]) - mem = mem_params + mem_bufs # in bytes + mem_params = sum([param.nelement() * param.element_size() for param in model.parameters()]) + mem_bufs = sum([buf.nelement() * buf.element_size() for buf in model.buffers()]) + mem = mem_params + mem_bufs # in bytes return mem @@ -377,11 +386,15 @@ def _fast_safetensors_reader(path: str): checkpoint = dict() device = torch.device("meta") with open(path, "rb") as f: - definition_len = int.from_bytes(f.read(8), 'little') + definition_len = int.from_bytes(f.read(8), "little") definition_json = f.read(definition_len) definition = json.loads(definition_json) - if "__metadata__" in definition and definition["__metadata__"].get("format", "pt") not in {"pt", "torch", "pytorch"}: + if "__metadata__" in definition and definition["__metadata__"].get("format", "pt") not in { + "pt", + "torch", + "pytorch", + }: raise Exception("Supported only pytorch safetensors files") definition.pop("__metadata__", None) @@ -400,6 +413,7 @@ def _fast_safetensors_reader(path: str): return checkpoint + def read_checkpoint_meta(path: Union[str, Path], scan: bool = False): if str(path).endswith(".safetensors"): try: @@ -411,25 +425,27 @@ def read_checkpoint_meta(path: Union[str, Path], scan: bool = False): if scan: scan_result = scan_file_path(path) if scan_result.infected_files != 0: - raise Exception(f"The model file \"{path}\" is potentially infected by malware. Aborting import.") + raise Exception(f'The model file "{path}" is potentially infected by malware. Aborting import.') checkpoint = torch.load(path, map_location=torch.device("meta")) return checkpoint + import warnings from diffusers import logging as diffusers_logging from transformers import logging as transformers_logging + class SilenceWarnings(object): def __init__(self): self.transformers_verbosity = transformers_logging.get_verbosity() self.diffusers_verbosity = diffusers_logging.get_verbosity() - + def __enter__(self): transformers_logging.set_verbosity_error() diffusers_logging.set_verbosity_error() - warnings.simplefilter('ignore') + warnings.simplefilter("ignore") def __exit__(self, type, value, traceback): transformers_logging.set_verbosity(self.transformers_verbosity) diffusers_logging.set_verbosity(self.diffusers_verbosity) - warnings.simplefilter('default') + warnings.simplefilter("default") diff --git a/invokeai/backend/model_management/models/controlnet.py b/invokeai/backend/model_management/models/controlnet.py index 41952af5d9..e075843a56 100644 --- a/invokeai/backend/model_management/models/controlnet.py +++ b/invokeai/backend/model_management/models/controlnet.py @@ -18,13 +18,15 @@ from .base import ( ) from invokeai.app.services.config import InvokeAIAppConfig + class ControlNetModelFormat(str, Enum): Checkpoint = "checkpoint" Diffusers = "diffusers" + class ControlNetModel(ModelBase): - #model_class: Type - #model_size: int + # model_class: Type + # model_size: int class DiffusersConfig(ModelConfigBase): model_format: Literal[ControlNetModelFormat.Diffusers] @@ -39,7 +41,7 @@ class ControlNetModel(ModelBase): try: config = EmptyConfigLoader.load_config(self.model_path, config_name="config.json") - #config = json.loads(os.path.join(self.model_path, "config.json")) + # config = json.loads(os.path.join(self.model_path, "config.json")) except: raise Exception("Invalid controlnet model! (config.json not found or invalid)") @@ -67,7 +69,7 @@ class ControlNetModel(ModelBase): raise Exception("There is no child models in controlnet model") model = None - for variant in ['fp16',None]: + for variant in ["fp16", None]: try: model = self.model_class.from_pretrained( self.model_path, @@ -79,7 +81,7 @@ class ControlNetModel(ModelBase): pass if not model: raise ModelNotFoundException() - + # calc more accurate size self.model_size = calc_model_size_by_data(model) return model @@ -105,29 +107,30 @@ class ControlNetModel(ModelBase): @classmethod def convert_if_required( - cls, - model_path: str, - output_path: str, - config: ModelConfigBase, - base_model: BaseModelType, - ) -> str: - if cls.detect_format(model_path) == ControlNetModelFormat.Checkpoint: - return _convert_controlnet_ckpt_and_cache( - model_path = model_path, - model_config = config.config, - output_path = output_path, - base_model = base_model, - ) - else: - return model_path - -@classmethod -def _convert_controlnet_ckpt_and_cache( cls, model_path: str, output_path: str, + config: ModelConfigBase, base_model: BaseModelType, - model_config: ControlNetModel.CheckpointConfig, + ) -> str: + if cls.detect_format(model_path) == ControlNetModelFormat.Checkpoint: + return _convert_controlnet_ckpt_and_cache( + model_path=model_path, + model_config=config.config, + output_path=output_path, + base_model=base_model, + ) + else: + return model_path + + +@classmethod +def _convert_controlnet_ckpt_and_cache( + cls, + model_path: str, + output_path: str, + base_model: BaseModelType, + model_config: ControlNetModel.CheckpointConfig, ) -> str: """ Convert the controlnet from checkpoint format to diffusers format, @@ -144,12 +147,13 @@ def _convert_controlnet_ckpt_and_cache( # to avoid circular import errors from ..convert_ckpt_to_diffusers import convert_controlnet_to_diffusers + convert_controlnet_to_diffusers( weights, output_path, - original_config_file = app_config.root_path / model_config, - image_size = 512, - scan_needed = True, - from_safetensors = weights.suffix == ".safetensors" + original_config_file=app_config.root_path / model_config, + image_size=512, + scan_needed=True, + from_safetensors=weights.suffix == ".safetensors", ) return output_path diff --git a/invokeai/backend/model_management/models/lora.py b/invokeai/backend/model_management/models/lora.py index eb771841ec..7cf87d8fe7 100644 --- a/invokeai/backend/model_management/models/lora.py +++ b/invokeai/backend/model_management/models/lora.py @@ -12,18 +12,21 @@ from .base import ( InvalidModelException, ModelNotFoundException, ) + # TODO: naming from ..lora import LoRAModel as LoRAModelRaw + class LoRAModelFormat(str, Enum): LyCORIS = "lycoris" Diffusers = "diffusers" + class LoRAModel(ModelBase): - #model_size: int + # model_size: int class Config(ModelConfigBase): - model_format: LoRAModelFormat # TODO: + model_format: LoRAModelFormat # TODO: def __init__(self, model_path: str, base_model: BaseModelType, model_type: ModelType): assert model_type == ModelType.Lora diff --git a/invokeai/backend/model_management/models/sdxl.py b/invokeai/backend/model_management/models/sdxl.py index ef0dd4c720..7fc3efb77c 100644 --- a/invokeai/backend/model_management/models/sdxl.py +++ b/invokeai/backend/model_management/models/sdxl.py @@ -15,12 +15,13 @@ from .base import ( ) from omegaconf import OmegaConf + class StableDiffusionXLModelFormat(str, Enum): Checkpoint = "checkpoint" Diffusers = "diffusers" - -class StableDiffusionXLModel(DiffusersModel): + +class StableDiffusionXLModel(DiffusersModel): # TODO: check that configs overwriten properly class DiffusersConfig(ModelConfigBase): model_format: Literal[StableDiffusionXLModelFormat.Diffusers] @@ -53,7 +54,7 @@ class StableDiffusionXLModel(DiffusersModel): else: checkpoint = read_checkpoint_meta(path) - checkpoint = checkpoint.get('state_dict', checkpoint) + checkpoint = checkpoint.get("state_dict", checkpoint) in_channels = checkpoint["model.diffusion_model.input_blocks.0.0.weight"].shape[1] elif model_format == StableDiffusionXLModelFormat.Diffusers: @@ -61,7 +62,7 @@ class StableDiffusionXLModel(DiffusersModel): if os.path.exists(unet_config_path): with open(unet_config_path, "r") as f: unet_config = json.loads(f.read()) - in_channels = unet_config['in_channels'] + in_channels = unet_config["in_channels"] else: raise Exception("Not supported stable diffusion diffusers format(possibly onnx?)") @@ -81,11 +82,10 @@ class StableDiffusionXLModel(DiffusersModel): if ckpt_config_path is None: # TO DO: implement picking pass - + return cls.create_config( path=path, model_format=model_format, - config=ckpt_config_path, variant=variant, ) @@ -112,17 +112,14 @@ class StableDiffusionXLModel(DiffusersModel): # The convert script adapted from the diffusers package uses # strings for the base model type. To avoid making too many # source code changes, we simply translate here - model_base_to_model_type = {BaseModelType.StableDiffusionXL: 'SDXL', - BaseModelType.StableDiffusionXLRefiner: 'SDXL-Refiner', - } if isinstance(config, cls.CheckpointConfig): from invokeai.backend.model_management.models.stable_diffusion import _convert_ckpt_and_cache + return _convert_ckpt_and_cache( version=base_model, model_config=config, output_path=output_path, - model_type=model_base_to_model_type[base_model], - use_safetensors=False, # corrupts sdxl models for some reason + use_safetensors=False, # corrupts sdxl models for some reason ) else: return model_path diff --git a/invokeai/backend/model_management/models/stable_diffusion.py b/invokeai/backend/model_management/models/stable_diffusion.py index 64dbd1c9ee..76b4833f9c 100644 --- a/invokeai/backend/model_management/models/stable_diffusion.py +++ b/invokeai/backend/model_management/models/stable_diffusion.py @@ -26,8 +26,8 @@ class StableDiffusion1ModelFormat(str, Enum): Checkpoint = "checkpoint" Diffusers = "diffusers" -class StableDiffusion1Model(DiffusersModel): +class StableDiffusion1Model(DiffusersModel): class DiffusersConfig(ModelConfigBase): model_format: Literal[StableDiffusion1ModelFormat.Diffusers] vae: Optional[str] = Field(None) @@ -38,7 +38,7 @@ class StableDiffusion1Model(DiffusersModel): vae: Optional[str] = Field(None) config: str variant: ModelVariantType - + def __init__(self, model_path: str, base_model: BaseModelType, model_type: ModelType): assert base_model == BaseModelType.StableDiffusion1 assert model_type == ModelType.Main @@ -59,7 +59,7 @@ class StableDiffusion1Model(DiffusersModel): else: checkpoint = read_checkpoint_meta(path) - checkpoint = checkpoint.get('state_dict', checkpoint) + checkpoint = checkpoint.get("state_dict", checkpoint) in_channels = checkpoint["model.diffusion_model.input_blocks.0.0.weight"].shape[1] elif model_format == StableDiffusion1ModelFormat.Diffusers: @@ -67,7 +67,7 @@ class StableDiffusion1Model(DiffusersModel): if os.path.exists(unet_config_path): with open(unet_config_path, "r") as f: unet_config = json.loads(f.read()) - in_channels = unet_config['in_channels'] + in_channels = unet_config["in_channels"] else: raise NotImplementedError(f"{path} is not a supported stable diffusion diffusers format") @@ -88,7 +88,6 @@ class StableDiffusion1Model(DiffusersModel): return cls.create_config( path=path, model_format=model_format, - config=ckpt_config_path, variant=variant, ) @@ -125,16 +124,17 @@ class StableDiffusion1Model(DiffusersModel): version=BaseModelType.StableDiffusion1, model_config=config, output_path=output_path, - ) + ) else: return model_path + class StableDiffusion2ModelFormat(str, Enum): Checkpoint = "checkpoint" Diffusers = "diffusers" -class StableDiffusion2Model(DiffusersModel): +class StableDiffusion2Model(DiffusersModel): # TODO: check that configs overwriten properly class DiffusersConfig(ModelConfigBase): model_format: Literal[StableDiffusion2ModelFormat.Diffusers] @@ -167,7 +167,7 @@ class StableDiffusion2Model(DiffusersModel): else: checkpoint = read_checkpoint_meta(path) - checkpoint = checkpoint.get('state_dict', checkpoint) + checkpoint = checkpoint.get("state_dict", checkpoint) in_channels = checkpoint["model.diffusion_model.input_blocks.0.0.weight"].shape[1] elif model_format == StableDiffusion2ModelFormat.Diffusers: @@ -175,7 +175,7 @@ class StableDiffusion2Model(DiffusersModel): if os.path.exists(unet_config_path): with open(unet_config_path, "r") as f: unet_config = json.loads(f.read()) - in_channels = unet_config['in_channels'] + in_channels = unet_config["in_channels"] else: raise Exception("Not supported stable diffusion diffusers format(possibly onnx?)") @@ -198,7 +198,6 @@ class StableDiffusion2Model(DiffusersModel): return cls.create_config( path=path, model_format=model_format, - config=ckpt_config_path, variant=variant, ) @@ -239,17 +238,19 @@ class StableDiffusion2Model(DiffusersModel): else: return model_path + # TODO: rework # pass precision - currently defaulting to fp16 def _convert_ckpt_and_cache( - version: BaseModelType, - model_config: Union[StableDiffusion1Model.CheckpointConfig, - StableDiffusion2Model.CheckpointConfig, - StableDiffusionXLModel.CheckpointConfig, - ], - output_path: str, - use_save_model: bool=False, - **kwargs, + version: BaseModelType, + model_config: Union[ + StableDiffusion1Model.CheckpointConfig, + StableDiffusion2Model.CheckpointConfig, + StableDiffusionXLModel.CheckpointConfig, + ], + output_path: str, + use_save_model: bool = False, + **kwargs, ) -> str: """ Convert the checkpoint model indicated in mconfig into a @@ -270,12 +271,14 @@ def _convert_ckpt_and_cache( from ..convert_ckpt_to_diffusers import convert_ckpt_to_diffusers from ...util.devices import choose_torch_device, torch_dtype - model_base_to_model_type = {BaseModelType.StableDiffusion1: 'FrozenCLIPEmbedder', - BaseModelType.StableDiffusion2: 'FrozenOpenCLIPEmbedder', - } - - logger.info(f'Converting {weights} to diffusers format') - with SilenceWarnings(): + model_base_to_model_type = { + BaseModelType.StableDiffusion1: "FrozenCLIPEmbedder", + BaseModelType.StableDiffusion2: "FrozenOpenCLIPEmbedder", + BaseModelType.StableDiffusionXL: "SDXL", + BaseModelType.StableDiffusionXLRefiner: "SDXL-Refiner", + } + logger.info(f"Converting {weights} to diffusers format") + with SilenceWarnings(): convert_ckpt_to_diffusers( weights, output_path, @@ -285,12 +288,13 @@ def _convert_ckpt_and_cache( original_config_file=config_file, extract_ema=True, scan_needed=True, - from_safetensors = weights.suffix == ".safetensors", - precision = torch_dtype(choose_torch_device()), + from_safetensors=weights.suffix == ".safetensors", + precision=torch_dtype(choose_torch_device()), **kwargs, ) return output_path + def _select_ckpt_config(version: BaseModelType, variant: ModelVariantType): ckpt_configs = { BaseModelType.StableDiffusion1: { @@ -298,7 +302,7 @@ def _select_ckpt_config(version: BaseModelType, variant: ModelVariantType): ModelVariantType.Inpaint: "v1-inpainting-inference.yaml", }, BaseModelType.StableDiffusion2: { - ModelVariantType.Normal: "v2-inference-v.yaml", # best guess, as we can't differentiate with base(512) + ModelVariantType.Normal: "v2-inference-v.yaml", # best guess, as we can't differentiate with base(512) ModelVariantType.Inpaint: "v2-inpainting-inference.yaml", ModelVariantType.Depth: "v2-midas-inference.yaml", }, @@ -320,8 +324,6 @@ def _select_ckpt_config(version: BaseModelType, variant: ModelVariantType): if config_path.is_relative_to(app_config.root_path): config_path = config_path.relative_to(app_config.root_path) return str(config_path) - + except: return None - - diff --git a/invokeai/backend/model_management/models/textual_inversion.py b/invokeai/backend/model_management/models/textual_inversion.py index eea0e85245..a949a15be1 100644 --- a/invokeai/backend/model_management/models/textual_inversion.py +++ b/invokeai/backend/model_management/models/textual_inversion.py @@ -11,11 +11,13 @@ from .base import ( ModelNotFoundException, InvalidModelException, ) + # TODO: naming from ..lora import TextualInversionModel as TextualInversionModelRaw + class TextualInversionModel(ModelBase): - #model_size: int + # model_size: int class Config(ModelConfigBase): model_format: None @@ -65,7 +67,7 @@ class TextualInversionModel(ModelBase): if os.path.isdir(path): if os.path.exists(os.path.join(path, "learned_embeds.bin")): - return None # diffusers-ti + return None # diffusers-ti if os.path.isfile(path): if any([path.endswith(f".{ext}") for ext in ["safetensors", "ckpt", "pt", "bin"]]): diff --git a/invokeai/backend/model_management/models/vae.py b/invokeai/backend/model_management/models/vae.py index f740615509..b15844bcf8 100644 --- a/invokeai/backend/model_management/models/vae.py +++ b/invokeai/backend/model_management/models/vae.py @@ -22,13 +22,15 @@ from invokeai.app.services.config import InvokeAIAppConfig from diffusers.utils import is_safetensors_available from omegaconf import OmegaConf + class VaeModelFormat(str, Enum): Checkpoint = "checkpoint" Diffusers = "diffusers" + class VaeModel(ModelBase): - #vae_class: Type - #model_size: int + # vae_class: Type + # model_size: int class Config(ModelConfigBase): model_format: VaeModelFormat @@ -39,7 +41,7 @@ class VaeModel(ModelBase): try: config = EmptyConfigLoader.load_config(self.model_path, config_name="config.json") - #config = json.loads(os.path.join(self.model_path, "config.json")) + # config = json.loads(os.path.join(self.model_path, "config.json")) except: raise Exception("Invalid vae model! (config.json not found or invalid)") @@ -95,7 +97,7 @@ class VaeModel(ModelBase): cls, model_path: str, output_path: str, - config: ModelConfigBase, # empty config or config of parent model + config: ModelConfigBase, # empty config or config of parent model base_model: BaseModelType, ) -> str: if cls.detect_format(model_path) == VaeModelFormat.Checkpoint: @@ -108,6 +110,7 @@ class VaeModel(ModelBase): else: return model_path + # TODO: rework def _convert_vae_ckpt_and_cache( weights_path: str, @@ -138,13 +141,14 @@ def _convert_vae_ckpt_and_cache( 2.1 - 768 """ image_size = 512 - + # return cached version if it exists if output_path.exists(): return output_path if base_model in {BaseModelType.StableDiffusion1, BaseModelType.StableDiffusion2}: from .stable_diffusion import _select_ckpt_config + # all sd models use same vae settings config_file = _select_ckpt_config(base_model, ModelVariantType.Normal) else: @@ -152,7 +156,8 @@ def _convert_vae_ckpt_and_cache( # this avoids circular import error from ..convert_ckpt_to_diffusers import convert_ldm_vae_to_diffusers - if weights_path.suffix == '.safetensors': + + if weights_path.suffix == ".safetensors": checkpoint = safetensors.torch.load_file(weights_path, device="cpu") else: checkpoint = torch.load(weights_path, map_location="cpu") @@ -161,15 +166,12 @@ def _convert_vae_ckpt_and_cache( if "state_dict" in checkpoint: checkpoint = checkpoint["state_dict"] - config = OmegaConf.load(app_config.root_path/config_file) + config = OmegaConf.load(app_config.root_path / config_file) vae_model = convert_ldm_vae_to_diffusers( - checkpoint = checkpoint, - vae_config = config, - image_size = image_size, - ) - vae_model.save_pretrained( - output_path, - safe_serialization=is_safetensors_available() + checkpoint=checkpoint, + vae_config=config, + image_size=image_size, ) + vae_model.save_pretrained(output_path, safe_serialization=is_safetensors_available()) return output_path diff --git a/invokeai/backend/stable_diffusion/diffusers_pipeline.py b/invokeai/backend/stable_diffusion/diffusers_pipeline.py index 8acfb100a6..624d47ff64 100644 --- a/invokeai/backend/stable_diffusion/diffusers_pipeline.py +++ b/invokeai/backend/stable_diffusion/diffusers_pipeline.py @@ -47,6 +47,7 @@ from .diffusion import ( ) from .offloading import FullyLoadedModelGroup, ModelGroup + @dataclass class PipelineIntermediateState: run_id: str @@ -72,7 +73,11 @@ class AddsMaskLatents: initial_image_latents: torch.Tensor def __call__( - self, latents: torch.Tensor, t: torch.Tensor, text_embeddings: torch.Tensor, **kwargs, + self, + latents: torch.Tensor, + t: torch.Tensor, + text_embeddings: torch.Tensor, + **kwargs, ) -> torch.Tensor: model_input = self.add_mask_channels(latents) return self.forward(model_input, t, text_embeddings, **kwargs) @@ -80,12 +85,8 @@ class AddsMaskLatents: def add_mask_channels(self, latents): batch_size = latents.size(0) # duplicate mask and latents for each batch - mask = einops.repeat( - self.mask, "b c h w -> (repeat b) c h w", repeat=batch_size - ) - image_latents = einops.repeat( - self.initial_image_latents, "b c h w -> (repeat b) c h w", repeat=batch_size - ) + mask = einops.repeat(self.mask, "b c h w -> (repeat b) c h w", repeat=batch_size) + image_latents = einops.repeat(self.initial_image_latents, "b c h w -> (repeat b) c h w", repeat=batch_size) # add mask and image as additional channels model_input, _ = einops.pack([latents, mask, image_latents], "b * h w") return model_input @@ -103,9 +104,7 @@ class AddsMaskGuidance: noise: torch.Tensor _debug: Optional[Callable] = None - def __call__( - self, step_output: Union[BaseOutput, SchedulerOutput], t: torch.Tensor, conditioning - ) -> BaseOutput: + def __call__(self, step_output: Union[BaseOutput, SchedulerOutput], t: torch.Tensor, conditioning) -> BaseOutput: output_class = step_output.__class__ # We'll create a new one with masked data. # The problem with taking SchedulerOutput instead of the model output is that we're less certain what's in it. @@ -116,11 +115,7 @@ class AddsMaskGuidance: # Mask anything that has the same shape as prev_sample, return others as-is. return output_class( { - k: ( - self.apply_mask(v, self._t_for_field(k, t)) - if are_like_tensors(prev_sample, v) - else v - ) + k: (self.apply_mask(v, self._t_for_field(k, t)) if are_like_tensors(prev_sample, v) else v) for k, v in step_output.items() } ) @@ -132,9 +127,7 @@ class AddsMaskGuidance: def apply_mask(self, latents: torch.Tensor, t) -> torch.Tensor: batch_size = latents.size(0) - mask = einops.repeat( - self.mask, "b c h w -> (repeat b) c h w", repeat=batch_size - ) + mask = einops.repeat(self.mask, "b c h w -> (repeat b) c h w", repeat=batch_size) if t.dim() == 0: # some schedulers expect t to be one-dimensional. # TODO: file diffusers bug about inconsistency? @@ -144,12 +137,8 @@ class AddsMaskGuidance: mask_latents = self.scheduler.add_noise(self.mask_latents, self.noise, t) # TODO: Do we need to also apply scheduler.scale_model_input? Or is add_noise appropriately scaled already? # mask_latents = self.scheduler.scale_model_input(mask_latents, t) - mask_latents = einops.repeat( - mask_latents, "b c h w -> (repeat b) c h w", repeat=batch_size - ) - masked_input = torch.lerp( - mask_latents.to(dtype=latents.dtype), latents, mask.to(dtype=latents.dtype) - ) + mask_latents = einops.repeat(mask_latents, "b c h w -> (repeat b) c h w", repeat=batch_size) + masked_input = torch.lerp(mask_latents.to(dtype=latents.dtype), latents, mask.to(dtype=latents.dtype)) if self._debug: self._debug(masked_input, f"t={t} lerped") return masked_input @@ -159,9 +148,7 @@ def trim_to_multiple_of(*args, multiple_of=8): return tuple((x - x % multiple_of) for x in args) -def image_resized_to_grid_as_tensor( - image: PIL.Image.Image, normalize: bool = True, multiple_of=8 -) -> torch.FloatTensor: +def image_resized_to_grid_as_tensor(image: PIL.Image.Image, normalize: bool = True, multiple_of=8) -> torch.FloatTensor: """ :param image: input image @@ -211,6 +198,7 @@ class GeneratorToCallbackinator(Generic[ParamType, ReturnType, CallbackType]): raise AssertionError("why was that an empty generator?") return result + @dataclass class ControlNetData: model: ControlNetModel = Field(default=None) @@ -341,9 +329,7 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): # FIXME: can't currently register control module # control_model=control_model, ) - self.invokeai_diffuser = InvokeAIDiffuserComponent( - self.unet, self._unet_forward - ) + self.invokeai_diffuser = InvokeAIDiffuserComponent(self.unet, self._unet_forward) self._model_group = FullyLoadedModelGroup(execution_device or self.unet.device) self._model_group.install(*self._submodels) @@ -354,11 +340,7 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): if xformers is available, use it, otherwise use sliced attention. """ config = InvokeAIAppConfig.get_config() - if ( - torch.cuda.is_available() - and is_xformers_available() - and not config.disable_xformers - ): + if torch.cuda.is_available() and is_xformers_available() and not config.disable_xformers: self.enable_xformers_memory_efficient_attention() else: if self.device.type == "cpu" or self.device.type == "mps": @@ -369,9 +351,7 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): raise ValueError(f"unrecognized device {self.device}") # input tensor of [1, 4, h/8, w/8] # output tensor of [16, (h/8 * w/8), (h/8 * w/8)] - bytes_per_element_needed_for_baddbmm_duplication = ( - latents.element_size() + 4 - ) + bytes_per_element_needed_for_baddbmm_duplication = latents.element_size() + 4 max_size_required_for_baddbmm = ( 16 * latents.size(dim=2) @@ -380,9 +360,7 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): * latents.size(dim=3) * bytes_per_element_needed_for_baddbmm_duplication ) - if max_size_required_for_baddbmm > ( - mem_free * 3.0 / 4.0 - ): # 3.3 / 4.0 is from old Invoke code + if max_size_required_for_baddbmm > (mem_free * 3.0 / 4.0): # 3.3 / 4.0 is from old Invoke code self.enable_attention_slicing(slice_size="max") elif torch.backends.mps.is_available(): # diffusers recommends always enabling for mps @@ -470,7 +448,7 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): control_data: List[ControlNetData] = None, ) -> tuple[torch.Tensor, Optional[AttentionMapSaver]]: if self.scheduler.config.get("cpu_only", False): - scheduler_device = torch.device('cpu') + scheduler_device = torch.device("cpu") else: scheduler_device = self._model_group.device_for(self.unet) @@ -488,7 +466,6 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): run_id=run_id, additional_guidance=additional_guidance, control_data=control_data, - callback=callback, ) return result.latents, result.attention_map_saver @@ -511,9 +488,9 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): additional_guidance = [] extra_conditioning_info = conditioning_data.extra with self.invokeai_diffuser.custom_attention_context( - self.invokeai_diffuser.model, - extra_conditioning_info=extra_conditioning_info, - step_count=len(self.scheduler.timesteps), + self.invokeai_diffuser.model, + extra_conditioning_info=extra_conditioning_info, + step_count=len(self.scheduler.timesteps), ): yield PipelineIntermediateState( run_id=run_id, @@ -607,16 +584,15 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): # that are combined at higher level to make control_mode enum # soft_injection determines whether to do per-layer re-weighting adjustment (if True) # or default weighting (if False) - soft_injection = (control_mode == "more_prompt" or control_mode == "more_control") + soft_injection = control_mode == "more_prompt" or control_mode == "more_control" # cfg_injection = determines whether to apply ControlNet to only the conditional (if True) # or the default both conditional and unconditional (if False) - cfg_injection = (control_mode == "more_control" or control_mode == "unbalanced") + cfg_injection = control_mode == "more_control" or control_mode == "unbalanced" first_control_step = math.floor(control_datum.begin_step_percent * total_step_count) last_control_step = math.ceil(control_datum.end_step_percent * total_step_count) # only apply controlnet if current step is within the controlnet's begin/end step range if step_index >= first_control_step and step_index <= last_control_step: - if cfg_injection: control_latent_input = unet_latent_input else: @@ -629,7 +605,10 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): encoder_hidden_states = conditioning_data.text_embeddings encoder_attention_mask = None else: - encoder_hidden_states, encoder_attention_mask = self.invokeai_diffuser._concat_conditionings_for_batch( + ( + encoder_hidden_states, + encoder_attention_mask, + ) = self.invokeai_diffuser._concat_conditionings_for_batch( conditioning_data.unconditioned_embeddings, conditioning_data.text_embeddings, ) @@ -646,9 +625,9 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): timestep=timestep, encoder_hidden_states=encoder_hidden_states, controlnet_cond=control_datum.image_tensor, - conditioning_scale=controlnet_weight, # controlnet specific, NOT the guidance scale + conditioning_scale=controlnet_weight, # controlnet specific, NOT the guidance scale encoder_attention_mask=encoder_attention_mask, - guess_mode=soft_injection, # this is still called guess_mode in diffusers ControlNetModel + guess_mode=soft_injection, # this is still called guess_mode in diffusers ControlNetModel return_dict=False, ) if cfg_injection: @@ -678,13 +657,11 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): step_index=step_index, total_step_count=total_step_count, down_block_additional_residuals=down_block_res_samples, # from controlnet(s) - mid_block_additional_residual=mid_block_res_sample, # from controlnet(s) + mid_block_additional_residual=mid_block_res_sample, # from controlnet(s) ) # compute the previous noisy sample x_t -> x_t-1 - step_output = self.scheduler.step( - noise_pred, timestep, latents, **conditioning_data.scheduler_args - ) + step_output = self.scheduler.step(noise_pred, timestep, latents, **conditioning_data.scheduler_args) # TODO: this additional_guidance extension point feels redundant with InvokeAIDiffusionComponent. # But the way things are now, scheduler runs _after_ that, so there was @@ -710,17 +687,16 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): # use of AddsMaskLatents. latents = AddsMaskLatents( self._unet_forward, - mask=torch.ones_like( - latents[:1, :1], device=latents.device, dtype=latents.dtype - ), - initial_image_latents=torch.zeros_like( - latents[:1], device=latents.device, dtype=latents.dtype - ), + mask=torch.ones_like(latents[:1, :1], device=latents.device, dtype=latents.dtype), + initial_image_latents=torch.zeros_like(latents[:1], device=latents.device, dtype=latents.dtype), ).add_mask_channels(latents) # First three args should be positional, not keywords, so torch hooks can see them. return self.unet( - latents, t, text_embeddings, cross_attention_kwargs=cross_attention_kwargs, + latents, + t, + text_embeddings, + cross_attention_kwargs=cross_attention_kwargs, **kwargs, ).sample @@ -774,9 +750,9 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): ) -> InvokeAIStableDiffusionPipelineOutput: timesteps, _ = self.get_img2img_timesteps(num_inference_steps, strength) result_latents, result_attention_maps = self.latents_from_embeddings( - latents=initial_latents if strength < 1.0 else torch.zeros_like( - initial_latents, device=initial_latents.device, dtype=initial_latents.dtype - ), + latents=initial_latents + if strength < 1.0 + else torch.zeros_like(initial_latents, device=initial_latents.device, dtype=initial_latents.dtype), num_inference_steps=num_inference_steps, conditioning_data=conditioning_data, timesteps=timesteps, @@ -797,14 +773,12 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): ) return self.check_for_safety(output, dtype=conditioning_data.dtype) - def get_img2img_timesteps( - self, num_inference_steps: int, strength: float, device=None - ) -> (torch.Tensor, int): + def get_img2img_timesteps(self, num_inference_steps: int, strength: float, device=None) -> (torch.Tensor, int): img2img_pipeline = StableDiffusionImg2ImgPipeline(**self.components) assert img2img_pipeline.scheduler is self.scheduler if self.scheduler.config.get("cpu_only", False): - scheduler_device = torch.device('cpu') + scheduler_device = torch.device("cpu") else: scheduler_device = self._model_group.device_for(self.unet) @@ -849,18 +823,16 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): # 6. Prepare latent variables # can't quite use upstream StableDiffusionImg2ImgPipeline.prepare_latents # because we have our own noise function - init_image_latents = self.non_noised_latents_from_image( - init_image, device=device, dtype=latents_dtype - ) + init_image_latents = self.non_noised_latents_from_image(init_image, device=device, dtype=latents_dtype) if seed is not None: set_seed(seed) noise = noise_func(init_image_latents) if mask.dim() == 3: mask = mask.unsqueeze(0) - latent_mask = tv_resize( - mask, init_image_latents.shape[-2:], T.InterpolationMode.BILINEAR - ).to(device=device, dtype=latents_dtype) + latent_mask = tv_resize(mask, init_image_latents.shape[-2:], T.InterpolationMode.BILINEAR).to( + device=device, dtype=latents_dtype + ) guidance: List[Callable] = [] @@ -868,22 +840,20 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): # You'd think the inpainting model wouldn't be paying attention to the area it is going to repaint # (that's why there's a mask!) but it seems to really want that blanked out. masked_init_image = init_image * torch.where(mask < 0.5, 1, 0) - masked_latents = self.non_noised_latents_from_image( - masked_init_image, device=device, dtype=latents_dtype - ) + masked_latents = self.non_noised_latents_from_image(masked_init_image, device=device, dtype=latents_dtype) # TODO: we should probably pass this in so we don't have to try/finally around setting it. self.invokeai_diffuser.model_forward_callback = AddsMaskLatents( self._unet_forward, latent_mask, masked_latents ) else: - guidance.append( - AddsMaskGuidance(latent_mask, init_image_latents, self.scheduler, noise) - ) + guidance.append(AddsMaskGuidance(latent_mask, init_image_latents, self.scheduler, noise)) try: result_latents, result_attention_maps = self.latents_from_embeddings( - latents=init_image_latents if strength < 1.0 else torch.zeros_like( + latents=init_image_latents + if strength < 1.0 + else torch.zeros_like( init_image_latents, device=init_image_latents.device, dtype=init_image_latents.dtype ), num_inference_steps=num_inference_steps, @@ -914,18 +884,14 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): with torch.inference_mode(): self._model_group.load(self.vae) init_latent_dist = self.vae.encode(init_image).latent_dist - init_latents = init_latent_dist.sample().to( - dtype=dtype - ) # FIXME: uses torch.randn. make reproducible! + init_latents = init_latent_dist.sample().to(dtype=dtype) # FIXME: uses torch.randn. make reproducible! init_latents = 0.18215 * init_latents return init_latents def check_for_safety(self, output, dtype): with torch.inference_mode(): - screened_images, has_nsfw_concept = self.run_safety_checker( - output.images, dtype=dtype - ) + screened_images, has_nsfw_concept = self.run_safety_checker(output.images, dtype=dtype) screened_attention_map_saver = None if has_nsfw_concept is None or not has_nsfw_concept: screened_attention_map_saver = output.attention_map_saver @@ -949,9 +915,8 @@ class StableDiffusionGeneratorPipeline(StableDiffusionPipeline): def debug_latents(self, latents, msg): from invokeai.backend.image_util import debug_image + with torch.inference_mode(): decoded = self.numpy_to_pil(self.decode_latents(latents)) for i, img in enumerate(decoded): - debug_image( - img, f"latents {msg} {i+1}/{len(decoded)}", debug_status=True - ) + debug_image(img, f"latents {msg} {i+1}/{len(decoded)}", debug_status=True) diff --git a/invokeai/backend/stable_diffusion/diffusion/cross_attention_control.py b/invokeai/backend/stable_diffusion/diffusion/cross_attention_control.py index 79a0982cfe..38763ebbee 100644 --- a/invokeai/backend/stable_diffusion/diffusion/cross_attention_control.py +++ b/invokeai/backend/stable_diffusion/diffusion/cross_attention_control.py @@ -17,6 +17,7 @@ from torch import nn import invokeai.backend.util.logging as logger from ...util import torch_dtype + class CrossAttentionType(enum.Enum): SELF = 1 TOKENS = 2 @@ -55,9 +56,7 @@ class Context: if name in self.self_cross_attention_module_identifiers: assert False, f"name {name} cannot appear more than once" self.self_cross_attention_module_identifiers.append(name) - for name, module in get_cross_attention_modules( - model, CrossAttentionType.TOKENS - ): + for name, module in get_cross_attention_modules(model, CrossAttentionType.TOKENS): if name in self.tokens_cross_attention_module_identifiers: assert False, f"name {name} cannot appear more than once" self.tokens_cross_attention_module_identifiers.append(name) @@ -68,9 +67,7 @@ class Context: else: self.tokens_cross_attention_action = Context.Action.SAVE - def request_apply_saved_attention_maps( - self, cross_attention_type: CrossAttentionType - ): + def request_apply_saved_attention_maps(self, cross_attention_type: CrossAttentionType): if cross_attention_type == CrossAttentionType.SELF: self.self_cross_attention_action = Context.Action.APPLY else: @@ -139,9 +136,7 @@ class Context: saved_attention_dict = self.saved_cross_attention_maps[identifier] if requested_dim is None: if saved_attention_dict["dim"] is not None: - raise RuntimeError( - f"dim mismatch: expected dim=None, have {saved_attention_dict['dim']}" - ) + raise RuntimeError(f"dim mismatch: expected dim=None, have {saved_attention_dict['dim']}") return saved_attention_dict["slices"][0] if saved_attention_dict["dim"] == requested_dim: @@ -154,21 +149,13 @@ class Context: if saved_attention_dict["dim"] is None: whole_saved_attention = saved_attention_dict["slices"][0] if requested_dim == 0: - return whole_saved_attention[ - requested_offset : requested_offset + slice_size - ] + return whole_saved_attention[requested_offset : requested_offset + slice_size] elif requested_dim == 1: - return whole_saved_attention[ - :, requested_offset : requested_offset + slice_size - ] + return whole_saved_attention[:, requested_offset : requested_offset + slice_size] - raise RuntimeError( - f"Cannot convert dim {saved_attention_dict['dim']} to requested dim {requested_dim}" - ) + raise RuntimeError(f"Cannot convert dim {saved_attention_dict['dim']} to requested dim {requested_dim}") - def get_slicing_strategy( - self, identifier: str - ) -> tuple[Optional[int], Optional[int]]: + def get_slicing_strategy(self, identifier: str) -> tuple[Optional[int], Optional[int]]: saved_attention = self.saved_cross_attention_maps.get(identifier, None) if saved_attention is None: return None, None @@ -201,9 +188,7 @@ class InvokeAICrossAttentionMixin: def set_attention_slice_wrangler( self, - wrangler: Optional[ - Callable[[nn.Module, torch.Tensor, int, int, int], torch.Tensor] - ], + wrangler: Optional[Callable[[nn.Module, torch.Tensor, int, int, int], torch.Tensor]], ): """ Set custom attention calculator to be called when attention is calculated @@ -219,14 +204,10 @@ class InvokeAICrossAttentionMixin: """ self.attention_slice_wrangler = wrangler - def set_slicing_strategy_getter( - self, getter: Optional[Callable[[nn.Module], tuple[int, int]]] - ): + def set_slicing_strategy_getter(self, getter: Optional[Callable[[nn.Module], tuple[int, int]]]): self.slicing_strategy_getter = getter - def set_attention_slice_calculated_callback( - self, callback: Optional[Callable[[torch.Tensor], None]] - ): + def set_attention_slice_calculated_callback(self, callback: Optional[Callable[[torch.Tensor], None]]): self.attention_slice_calculated_callback = callback def einsum_lowest_level(self, query, key, value, dim, offset, slice_size): @@ -247,45 +228,31 @@ class InvokeAICrossAttentionMixin: ) # calculate attention slice by taking the best scores for each latent pixel - default_attention_slice = attention_scores.softmax( - dim=-1, dtype=attention_scores.dtype - ) + default_attention_slice = attention_scores.softmax(dim=-1, dtype=attention_scores.dtype) attention_slice_wrangler = self.attention_slice_wrangler if attention_slice_wrangler is not None: - attention_slice = attention_slice_wrangler( - self, default_attention_slice, dim, offset, slice_size - ) + attention_slice = attention_slice_wrangler(self, default_attention_slice, dim, offset, slice_size) else: attention_slice = default_attention_slice if self.attention_slice_calculated_callback is not None: - self.attention_slice_calculated_callback( - attention_slice, dim, offset, slice_size - ) + self.attention_slice_calculated_callback(attention_slice, dim, offset, slice_size) hidden_states = torch.bmm(attention_slice, value) return hidden_states def einsum_op_slice_dim0(self, q, k, v, slice_size): - r = torch.zeros( - q.shape[0], q.shape[1], v.shape[2], device=q.device, dtype=q.dtype - ) + r = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device, dtype=q.dtype) for i in range(0, q.shape[0], slice_size): end = i + slice_size - r[i:end] = self.einsum_lowest_level( - q[i:end], k[i:end], v[i:end], dim=0, offset=i, slice_size=slice_size - ) + r[i:end] = self.einsum_lowest_level(q[i:end], k[i:end], v[i:end], dim=0, offset=i, slice_size=slice_size) return r def einsum_op_slice_dim1(self, q, k, v, slice_size): - r = torch.zeros( - q.shape[0], q.shape[1], v.shape[2], device=q.device, dtype=q.dtype - ) + r = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device, dtype=q.dtype) for i in range(0, q.shape[1], slice_size): end = i + slice_size - r[:, i:end] = self.einsum_lowest_level( - q[:, i:end], k, v, dim=1, offset=i, slice_size=slice_size - ) + r[:, i:end] = self.einsum_lowest_level(q[:, i:end], k, v, dim=1, offset=i, slice_size=slice_size) return r def einsum_op_mps_v1(self, q, k, v): @@ -353,6 +320,7 @@ def restore_default_cross_attention( else: remove_attention_function(model) + def setup_cross_attention_control_attention_processors(unet: UNet2DConditionModel, context: Context): """ Inject attention parameters and functions into the passed in model to enable cross attention editing. @@ -372,7 +340,7 @@ def setup_cross_attention_control_attention_processors(unet: UNet2DConditionMode indices = torch.arange(max_length, dtype=torch.long) for name, a0, a1, b0, b1 in context.arguments.edit_opcodes: if b0 < max_length: - if name == "equal":# or (name == "replace" and a1 - a0 == b1 - b0): + if name == "equal": # or (name == "replace" and a1 - a0 == b1 - b0): # these tokens have not been edited indices[b0:b1] = indices_target[a0:a1] mask[b0:b1] = 1 @@ -386,16 +354,14 @@ def setup_cross_attention_control_attention_processors(unet: UNet2DConditionMode else: # try to re-use an existing slice size default_slice_size = 4 - slice_size = next((p.slice_size for p in old_attn_processors.values() if type(p) is SlicedAttnProcessor), default_slice_size) + slice_size = next( + (p.slice_size for p in old_attn_processors.values() if type(p) is SlicedAttnProcessor), default_slice_size + ) unet.set_attn_processor(SlicedSwapCrossAttnProcesser(slice_size=slice_size)) -def get_cross_attention_modules( - model, which: CrossAttentionType -) -> list[tuple[str, InvokeAICrossAttentionMixin]]: - cross_attention_class: type = ( - InvokeAIDiffusersCrossAttention - ) +def get_cross_attention_modules(model, which: CrossAttentionType) -> list[tuple[str, InvokeAICrossAttentionMixin]]: + cross_attention_class: type = InvokeAIDiffusersCrossAttention which_attn = "attn1" if which is CrossAttentionType.SELF else "attn2" attention_module_tuples = [ (name, module) @@ -420,9 +386,7 @@ def get_cross_attention_modules( def inject_attention_function(unet, context: Context): # ORIGINAL SOURCE CODE: https://github.com/huggingface/diffusers/blob/91ddd2a25b848df0fa1262d4f1cd98c7ccb87750/src/diffusers/models/attention.py#L276 - def attention_slice_wrangler( - module, suggested_attention_slice: torch.Tensor, dim, offset, slice_size - ): + def attention_slice_wrangler(module, suggested_attention_slice: torch.Tensor, dim, offset, slice_size): # memory_usage = suggested_attention_slice.element_size() * suggested_attention_slice.nelement() attention_slice = suggested_attention_slice @@ -430,9 +394,7 @@ def inject_attention_function(unet, context: Context): if context.get_should_save_maps(module.identifier): # print(module.identifier, "saving suggested_attention_slice of shape", # suggested_attention_slice.shape, "dim", dim, "offset", offset) - slice_to_save = ( - attention_slice.to("cpu") if dim is not None else attention_slice - ) + slice_to_save = attention_slice.to("cpu") if dim is not None else attention_slice context.save_slice( module.identifier, slice_to_save, @@ -442,31 +404,20 @@ def inject_attention_function(unet, context: Context): ) elif context.get_should_apply_saved_maps(module.identifier): # print(module.identifier, "applying saved attention slice for dim", dim, "offset", offset) - saved_attention_slice = context.get_slice( - module.identifier, dim, offset, slice_size - ) + saved_attention_slice = context.get_slice(module.identifier, dim, offset, slice_size) # slice may have been offloaded to CPU - saved_attention_slice = saved_attention_slice.to( - suggested_attention_slice.device - ) + saved_attention_slice = saved_attention_slice.to(suggested_attention_slice.device) if context.is_tokens_cross_attention(module.identifier): index_map = context.cross_attention_index_map - remapped_saved_attention_slice = torch.index_select( - saved_attention_slice, -1, index_map - ) + remapped_saved_attention_slice = torch.index_select(saved_attention_slice, -1, index_map) this_attention_slice = suggested_attention_slice - mask = context.cross_attention_mask.to( - torch_dtype(suggested_attention_slice.device) - ) + mask = context.cross_attention_mask.to(torch_dtype(suggested_attention_slice.device)) saved_mask = mask this_mask = 1 - mask - attention_slice = ( - remapped_saved_attention_slice * saved_mask - + this_attention_slice * this_mask - ) + attention_slice = remapped_saved_attention_slice * saved_mask + this_attention_slice * this_mask else: # just use everything attention_slice = saved_attention_slice @@ -480,14 +431,10 @@ def inject_attention_function(unet, context: Context): module.identifier = identifier try: module.set_attention_slice_wrangler(attention_slice_wrangler) - module.set_slicing_strategy_getter( - lambda module: context.get_slicing_strategy(identifier) - ) + module.set_slicing_strategy_getter(lambda module: context.get_slicing_strategy(identifier)) except AttributeError as e: if is_attribute_error_about(e, "set_attention_slice_wrangler"): - print( - f"TODO: implement set_attention_slice_wrangler for {type(module)}" - ) # TODO + print(f"TODO: implement set_attention_slice_wrangler for {type(module)}") # TODO else: raise @@ -503,9 +450,7 @@ def remove_attention_function(unet): module.set_slicing_strategy_getter(None) except AttributeError as e: if is_attribute_error_about(e, "set_attention_slice_wrangler"): - print( - f"TODO: implement set_attention_slice_wrangler for {type(module)}" - ) + print(f"TODO: implement set_attention_slice_wrangler for {type(module)}") else: raise @@ -530,9 +475,7 @@ def get_mem_free_total(device): return mem_free_total -class InvokeAIDiffusersCrossAttention( - diffusers.models.attention.Attention, InvokeAICrossAttentionMixin -): +class InvokeAIDiffusersCrossAttention(diffusers.models.attention.Attention, InvokeAICrossAttentionMixin): def __init__(self, **kwargs): super().__init__(**kwargs) InvokeAICrossAttentionMixin.__init__(self) @@ -641,11 +584,7 @@ class SlicedSwapCrossAttnProcesser(SlicedAttnProcessor): # kwargs swap_cross_attn_context: SwapCrossAttnContext = None, ): - attention_type = ( - CrossAttentionType.SELF - if encoder_hidden_states is None - else CrossAttentionType.TOKENS - ) + attention_type = CrossAttentionType.SELF if encoder_hidden_states is None else CrossAttentionType.TOKENS # if cross-attention control is not in play, just call through to the base implementation. if ( @@ -654,9 +593,7 @@ class SlicedSwapCrossAttnProcesser(SlicedAttnProcessor): or not swap_cross_attn_context.wants_cross_attention_control(attention_type) ): # print(f"SwapCrossAttnContext for {attention_type} not active - passing request to superclass") - return super().__call__( - attn, hidden_states, encoder_hidden_states, attention_mask - ) + return super().__call__(attn, hidden_states, encoder_hidden_states, attention_mask) # else: # print(f"SwapCrossAttnContext for {attention_type} active") @@ -699,18 +636,10 @@ class SlicedSwapCrossAttnProcesser(SlicedAttnProcessor): query_slice = query[start_idx:end_idx] original_key_slice = original_text_key[start_idx:end_idx] modified_key_slice = modified_text_key[start_idx:end_idx] - attn_mask_slice = ( - attention_mask[start_idx:end_idx] - if attention_mask is not None - else None - ) + attn_mask_slice = attention_mask[start_idx:end_idx] if attention_mask is not None else None - original_attn_slice = attn.get_attention_scores( - query_slice, original_key_slice, attn_mask_slice - ) - modified_attn_slice = attn.get_attention_scores( - query_slice, modified_key_slice, attn_mask_slice - ) + original_attn_slice = attn.get_attention_scores(query_slice, original_key_slice, attn_mask_slice) + modified_attn_slice = attn.get_attention_scores(query_slice, modified_key_slice, attn_mask_slice) # because the prompt modifications may result in token sequences shifted forwards or backwards, # the original attention probabilities must be remapped to account for token index changes in the @@ -722,9 +651,7 @@ class SlicedSwapCrossAttnProcesser(SlicedAttnProcessor): # only some tokens taken from the original attention probabilities. this is controlled by the mask. mask = swap_cross_attn_context.mask inverse_mask = 1 - mask - attn_slice = ( - remapped_original_attn_slice * mask + modified_attn_slice * inverse_mask - ) + attn_slice = remapped_original_attn_slice * mask + modified_attn_slice * inverse_mask del remapped_original_attn_slice, modified_attn_slice @@ -744,6 +671,4 @@ class SlicedSwapCrossAttnProcesser(SlicedAttnProcessor): class SwapCrossAttnProcessor(SlicedSwapCrossAttnProcesser): def __init__(self): - super(SwapCrossAttnProcessor, self).__init__( - slice_size=int(1e9) - ) # massive slice size = don't slice + super(SwapCrossAttnProcessor, self).__init__(slice_size=int(1e9)) # massive slice size = don't slice diff --git a/invokeai/backend/stable_diffusion/diffusion/cross_attention_map_saving.py b/invokeai/backend/stable_diffusion/diffusion/cross_attention_map_saving.py index c489c2f0a9..b0174a455e 100644 --- a/invokeai/backend/stable_diffusion/diffusion/cross_attention_map_saving.py +++ b/invokeai/backend/stable_diffusion/diffusion/cross_attention_map_saving.py @@ -59,9 +59,7 @@ class AttentionMapSaver: for key, maps in self.collated_maps.items(): # maps has shape [(H*W), N] for N tokens # but we want [N, H, W] - this_scale_factor = math.sqrt( - maps.shape[0] / (latents_width * latents_height) - ) + this_scale_factor = math.sqrt(maps.shape[0] / (latents_width * latents_height)) this_maps_height = int(float(latents_height) * this_scale_factor) this_maps_width = int(float(latents_width) * this_scale_factor) # and we need to do some dimension juggling @@ -72,9 +70,7 @@ class AttentionMapSaver: # scale to output size if necessary if this_scale_factor != 1: - maps = tv_resize( - maps, [latents_height, latents_width], InterpolationMode.BICUBIC - ) + maps = tv_resize(maps, [latents_height, latents_width], InterpolationMode.BICUBIC) # normalize maps_min = torch.min(maps) @@ -83,9 +79,7 @@ class AttentionMapSaver: maps_normalized = (maps - maps_min) / maps_range # expand to (-0.1, 1.1) and clamp maps_normalized_expanded = maps_normalized * 1.1 - 0.05 - maps_normalized_expanded_clamped = torch.clamp( - maps_normalized_expanded, 0, 1 - ) + maps_normalized_expanded_clamped = torch.clamp(maps_normalized_expanded, 0, 1) # merge together, producing a vertical stack maps_stacked = torch.reshape( diff --git a/invokeai/backend/stable_diffusion/diffusion/shared_invokeai_diffusion.py b/invokeai/backend/stable_diffusion/diffusion/shared_invokeai_diffusion.py index f44578cd47..272518e928 100644 --- a/invokeai/backend/stable_diffusion/diffusion/shared_invokeai_diffusion.py +++ b/invokeai/backend/stable_diffusion/diffusion/shared_invokeai_diffusion.py @@ -31,6 +31,7 @@ ModelForwardCallback: TypeAlias = Union[ Callable[[torch.Tensor, torch.Tensor, torch.Tensor], torch.Tensor], ] + @dataclass(frozen=True) class PostprocessingSettings: threshold: float @@ -81,14 +82,12 @@ class InvokeAIDiffuserComponent: @contextmanager def custom_attention_context( cls, - unet: UNet2DConditionModel, # note: also may futz with the text encoder depending on requested LoRAs + unet: UNet2DConditionModel, # note: also may futz with the text encoder depending on requested LoRAs extra_conditioning_info: Optional[ExtraConditioningInfo], - step_count: int + step_count: int, ): old_attn_processors = None - if extra_conditioning_info and ( - extra_conditioning_info.wants_cross_attention_control - ): + if extra_conditioning_info and (extra_conditioning_info.wants_cross_attention_control): old_attn_processors = unet.attn_processors # Load lora conditions into the model if extra_conditioning_info.wants_cross_attention_control: @@ -116,27 +115,15 @@ class InvokeAIDiffuserComponent: return saver.add_attention_maps(slice, key) - tokens_cross_attention_modules = get_cross_attention_modules( - self.model, CrossAttentionType.TOKENS - ) + tokens_cross_attention_modules = get_cross_attention_modules(self.model, CrossAttentionType.TOKENS) for identifier, module in tokens_cross_attention_modules: - key = ( - "down" - if identifier.startswith("down") - else "up" - if identifier.startswith("up") - else "mid" - ) + key = "down" if identifier.startswith("down") else "up" if identifier.startswith("up") else "mid" module.set_attention_slice_calculated_callback( - lambda slice, dim, offset, slice_size, key=key: callback( - slice, dim, offset, slice_size, key - ) + lambda slice, dim, offset, slice_size, key=key: callback(slice, dim, offset, slice_size, key) ) def remove_attention_map_saving(self): - tokens_cross_attention_modules = get_cross_attention_modules( - self.model, CrossAttentionType.TOKENS - ) + tokens_cross_attention_modules = get_cross_attention_modules(self.model, CrossAttentionType.TOKENS) for _, module in tokens_cross_attention_modules: module.set_attention_slice_calculated_callback(None) @@ -171,10 +158,8 @@ class InvokeAIDiffuserComponent: context: Context = self.cross_attention_control_context if self.cross_attention_control_context is not None: percent_through = step_index / total_step_count - cross_attention_control_types_to_do = ( - context.get_active_cross_attention_control_types_for_step( - percent_through - ) + cross_attention_control_types_to_do = context.get_active_cross_attention_control_types_for_step( + percent_through ) wants_cross_attention_control = len(cross_attention_control_types_to_do) > 0 @@ -182,7 +167,11 @@ class InvokeAIDiffuserComponent: if wants_hybrid_conditioning: unconditioned_next_x, conditioned_next_x = self._apply_hybrid_conditioning( - x, sigma, unconditioning, conditioning, **kwargs, + x, + sigma, + unconditioning, + conditioning, + **kwargs, ) elif wants_cross_attention_control: ( @@ -201,7 +190,11 @@ class InvokeAIDiffuserComponent: unconditioned_next_x, conditioned_next_x, ) = self._apply_standard_conditioning_sequentially( - x, sigma, unconditioning, conditioning, **kwargs, + x, + sigma, + unconditioning, + conditioning, + **kwargs, ) else: @@ -209,12 +202,18 @@ class InvokeAIDiffuserComponent: unconditioned_next_x, conditioned_next_x, ) = self._apply_standard_conditioning( - x, sigma, unconditioning, conditioning, **kwargs, + x, + sigma, + unconditioning, + conditioning, + **kwargs, ) combined_next_x = self._combine( # unconditioned_next_x, conditioned_next_x, unconditional_guidance_scale - unconditioned_next_x, conditioned_next_x, guidance_scale + unconditioned_next_x, + conditioned_next_x, + guidance_scale, ) return combined_next_x @@ -229,37 +228,47 @@ class InvokeAIDiffuserComponent: ) -> torch.Tensor: if postprocessing_settings is not None: percent_through = step_index / total_step_count - latents = self.apply_threshold( - postprocessing_settings, latents, percent_through - ) - latents = self.apply_symmetry( - postprocessing_settings, latents, percent_through - ) + latents = self.apply_threshold(postprocessing_settings, latents, percent_through) + latents = self.apply_symmetry(postprocessing_settings, latents, percent_through) return latents def _concat_conditionings_for_batch(self, unconditioning, conditioning): def _pad_conditioning(cond, target_len, encoder_attention_mask): - conditioning_attention_mask = torch.ones((cond.shape[0], cond.shape[1]), device=cond.device, dtype=cond.dtype) + conditioning_attention_mask = torch.ones( + (cond.shape[0], cond.shape[1]), device=cond.device, dtype=cond.dtype + ) if cond.shape[1] < max_len: - conditioning_attention_mask = torch.cat([ - conditioning_attention_mask, - torch.zeros((cond.shape[0], max_len - cond.shape[1]), device=cond.device, dtype=cond.dtype), - ], dim=1) + conditioning_attention_mask = torch.cat( + [ + conditioning_attention_mask, + torch.zeros((cond.shape[0], max_len - cond.shape[1]), device=cond.device, dtype=cond.dtype), + ], + dim=1, + ) - cond = torch.cat([ - cond, - torch.zeros((cond.shape[0], max_len - cond.shape[1], cond.shape[2]), device=cond.device, dtype=cond.dtype), - ], dim=1) + cond = torch.cat( + [ + cond, + torch.zeros( + (cond.shape[0], max_len - cond.shape[1], cond.shape[2]), + device=cond.device, + dtype=cond.dtype, + ), + ], + dim=1, + ) if encoder_attention_mask is None: encoder_attention_mask = conditioning_attention_mask else: - encoder_attention_mask = torch.cat([ - encoder_attention_mask, - conditioning_attention_mask, - ]) - + encoder_attention_mask = torch.cat( + [ + encoder_attention_mask, + conditioning_attention_mask, + ] + ) + return cond, encoder_attention_mask encoder_attention_mask = None @@ -277,11 +286,11 @@ class InvokeAIDiffuserComponent: x_twice = torch.cat([x] * 2) sigma_twice = torch.cat([sigma] * 2) - both_conditionings, encoder_attention_mask = self._concat_conditionings_for_batch( - unconditioning, conditioning - ) + both_conditionings, encoder_attention_mask = self._concat_conditionings_for_batch(unconditioning, conditioning) both_results = self.model_forward_callback( - x_twice, sigma_twice, both_conditionings, + x_twice, + sigma_twice, + both_conditionings, encoder_attention_mask=encoder_attention_mask, **kwargs, ) @@ -312,13 +321,17 @@ class InvokeAIDiffuserComponent: uncond_mid_block, cond_mid_block = mid_block_additional_residual.chunk(2) unconditioned_next_x = self.model_forward_callback( - x, sigma, unconditioning, + x, + sigma, + unconditioning, down_block_additional_residuals=uncond_down_block, mid_block_additional_residual=uncond_mid_block, **kwargs, ) conditioned_next_x = self.model_forward_callback( - x, sigma, conditioning, + x, + sigma, + conditioning, down_block_additional_residuals=cond_down_block, mid_block_additional_residual=cond_mid_block, **kwargs, @@ -335,13 +348,15 @@ class InvokeAIDiffuserComponent: for k in conditioning: if isinstance(conditioning[k], list): both_conditionings[k] = [ - torch.cat([unconditioning[k][i], conditioning[k][i]]) - for i in range(len(conditioning[k])) + torch.cat([unconditioning[k][i], conditioning[k][i]]) for i in range(len(conditioning[k])) ] else: both_conditionings[k] = torch.cat([unconditioning[k], conditioning[k]]) unconditioned_next_x, conditioned_next_x = self.model_forward_callback( - x_twice, sigma_twice, both_conditionings, **kwargs, + x_twice, + sigma_twice, + both_conditionings, + **kwargs, ).chunk(2) return unconditioned_next_x, conditioned_next_x @@ -388,9 +403,7 @@ class InvokeAIDiffuserComponent: ) # do requested cross attention types for conditioning (positive prompt) - cross_attn_processor_context.cross_attention_types_to_do = ( - cross_attention_control_types_to_do - ) + cross_attn_processor_context.cross_attention_types_to_do = cross_attention_control_types_to_do conditioned_next_x = self.model_forward_callback( x, sigma, @@ -414,19 +427,14 @@ class InvokeAIDiffuserComponent: latents: torch.Tensor, percent_through: float, ) -> torch.Tensor: - if ( - postprocessing_settings.threshold is None - or postprocessing_settings.threshold == 0.0 - ): + if postprocessing_settings.threshold is None or postprocessing_settings.threshold == 0.0: return latents threshold = postprocessing_settings.threshold warmup = postprocessing_settings.warmup if percent_through < warmup: - current_threshold = threshold + threshold * 5 * ( - 1 - (percent_through / warmup) - ) + current_threshold = threshold + threshold * 5 * (1 - (percent_through / warmup)) else: current_threshold = threshold @@ -440,18 +448,10 @@ class InvokeAIDiffuserComponent: if self.debug_thresholding: std, mean = [i.item() for i in torch.std_mean(latents)] - outside = torch.count_nonzero( - (latents < -current_threshold) | (latents > current_threshold) - ) - logger.info( - f"Threshold: %={percent_through} threshold={current_threshold:.3f} (of {threshold:.3f})" - ) - logger.debug( - f"min, mean, max = {minval:.3f}, {mean:.3f}, {maxval:.3f}\tstd={std}" - ) - logger.debug( - f"{outside / latents.numel() * 100:.2f}% values outside threshold" - ) + outside = torch.count_nonzero((latents < -current_threshold) | (latents > current_threshold)) + logger.info(f"Threshold: %={percent_through} threshold={current_threshold:.3f} (of {threshold:.3f})") + logger.debug(f"min, mean, max = {minval:.3f}, {mean:.3f}, {maxval:.3f}\tstd={std}") + logger.debug(f"{outside / latents.numel() * 100:.2f}% values outside threshold") if maxval < current_threshold and minval > -current_threshold: return latents @@ -464,25 +464,17 @@ class InvokeAIDiffuserComponent: latents = torch.clone(latents) maxval = np.clip(maxval * scale, 1, current_threshold) num_altered += torch.count_nonzero(latents > maxval) - latents[latents > maxval] = ( - torch.rand_like(latents[latents > maxval]) * maxval - ) + latents[latents > maxval] = torch.rand_like(latents[latents > maxval]) * maxval if minval < -current_threshold: latents = torch.clone(latents) minval = np.clip(minval * scale, -current_threshold, -1) num_altered += torch.count_nonzero(latents < minval) - latents[latents < minval] = ( - torch.rand_like(latents[latents < minval]) * minval - ) + latents[latents < minval] = torch.rand_like(latents[latents < minval]) * minval if self.debug_thresholding: - logger.debug( - f"min, , max = {minval:.3f}, , {maxval:.3f}\t(scaled by {scale})" - ) - logger.debug( - f"{num_altered / latents.numel() * 100:.2f}% values altered" - ) + logger.debug(f"min, , max = {minval:.3f}, , {maxval:.3f}\t(scaled by {scale})") + logger.debug(f"{num_altered / latents.numel() * 100:.2f}% values altered") return latents @@ -501,15 +493,11 @@ class InvokeAIDiffuserComponent: # Check for out of bounds h_symmetry_time_pct = postprocessing_settings.h_symmetry_time_pct - if h_symmetry_time_pct is not None and ( - h_symmetry_time_pct <= 0.0 or h_symmetry_time_pct > 1.0 - ): + if h_symmetry_time_pct is not None and (h_symmetry_time_pct <= 0.0 or h_symmetry_time_pct > 1.0): h_symmetry_time_pct = None v_symmetry_time_pct = postprocessing_settings.v_symmetry_time_pct - if v_symmetry_time_pct is not None and ( - v_symmetry_time_pct <= 0.0 or v_symmetry_time_pct > 1.0 - ): + if v_symmetry_time_pct is not None and (v_symmetry_time_pct <= 0.0 or v_symmetry_time_pct > 1.0): v_symmetry_time_pct = None dev = latents.device.type @@ -554,9 +542,7 @@ class InvokeAIDiffuserComponent: def estimate_percent_through(self, step_index, sigma): if step_index is not None and self.cross_attention_control_context is not None: # percent_through will never reach 1.0 (but this is intended) - return float(step_index) / float( - self.cross_attention_control_context.step_count - ) + return float(step_index) / float(self.cross_attention_control_context.step_count) # find the best possible index of the current sigma in the sigma sequence smaller_sigmas = torch.nonzero(self.model.sigmas <= sigma) sigma_index = smaller_sigmas[-1].item() if smaller_sigmas.shape[0] > 0 else 0 @@ -567,19 +553,13 @@ class InvokeAIDiffuserComponent: # todo: make this work @classmethod - def apply_conjunction( - cls, x, t, forward_func, uc, c_or_weighted_c_list, global_guidance_scale - ): + def apply_conjunction(cls, x, t, forward_func, uc, c_or_weighted_c_list, global_guidance_scale): x_in = torch.cat([x] * 2) t_in = torch.cat([t] * 2) # aka sigmas deltas = None uncond_latents = None - weighted_cond_list = ( - c_or_weighted_c_list - if type(c_or_weighted_c_list) is list - else [(c_or_weighted_c_list, 1)] - ) + weighted_cond_list = c_or_weighted_c_list if type(c_or_weighted_c_list) is list else [(c_or_weighted_c_list, 1)] # below is fugly omg conditionings = [uc] + [c for c, weight in weighted_cond_list] @@ -608,15 +588,11 @@ class InvokeAIDiffuserComponent: deltas = torch.cat((deltas, latents_b - uncond_latents)) # merge the weighted deltas together into a single merged delta - per_delta_weights = torch.tensor( - weights[1:], dtype=deltas.dtype, device=deltas.device - ) + per_delta_weights = torch.tensor(weights[1:], dtype=deltas.dtype, device=deltas.device) normalize = False if normalize: per_delta_weights /= torch.sum(per_delta_weights) - reshaped_weights = per_delta_weights.reshape( - per_delta_weights.shape + (1, 1, 1) - ) + reshaped_weights = per_delta_weights.reshape(per_delta_weights.shape + (1, 1, 1)) deltas_merged = torch.sum(deltas * reshaped_weights, dim=0, keepdim=True) # old_return_value = super().forward(x, sigma, uncond, cond, cond_scale) diff --git a/invokeai/backend/stable_diffusion/image_degradation/bsrgan.py b/invokeai/backend/stable_diffusion/image_degradation/bsrgan.py index 1760206073..493c8be781 100644 --- a/invokeai/backend/stable_diffusion/image_degradation/bsrgan.py +++ b/invokeai/backend/stable_diffusion/image_degradation/bsrgan.py @@ -261,9 +261,7 @@ def srmd_degradation(x, k, sf=3): year={2018} } """ - x = ndimage.filters.convolve( - x, np.expand_dims(k, axis=2), mode="wrap" - ) # 'nearest' | 'mirror' + x = ndimage.filters.convolve(x, np.expand_dims(k, axis=2), mode="wrap") # 'nearest' | 'mirror' x = bicubic_degradation(x, sf=sf) return x @@ -389,21 +387,15 @@ def add_Gaussian_noise(img, noise_level1=2, noise_level2=25): noise_level = random.randint(noise_level1, noise_level2) rnum = np.random.rand() if rnum > 0.6: # add color Gaussian noise - img = img + np.random.normal(0, noise_level / 255.0, img.shape).astype( - np.float32 - ) + img = img + np.random.normal(0, noise_level / 255.0, img.shape).astype(np.float32) elif rnum < 0.4: # add grayscale Gaussian noise - img = img + np.random.normal( - 0, noise_level / 255.0, (*img.shape[:2], 1) - ).astype(np.float32) + img = img + np.random.normal(0, noise_level / 255.0, (*img.shape[:2], 1)).astype(np.float32) else: # add noise L = noise_level2 / 255.0 D = np.diag(np.random.rand(3)) U = orth(np.random.rand(3, 3)) conv = np.dot(np.dot(np.transpose(U), D), U) - img = img + np.random.multivariate_normal( - [0, 0, 0], np.abs(L**2 * conv), img.shape[:2] - ).astype(np.float32) + img = img + np.random.multivariate_normal([0, 0, 0], np.abs(L**2 * conv), img.shape[:2]).astype(np.float32) img = np.clip(img, 0.0, 1.0) return img @@ -413,21 +405,15 @@ def add_speckle_noise(img, noise_level1=2, noise_level2=25): img = np.clip(img, 0.0, 1.0) rnum = random.random() if rnum > 0.6: - img += img * np.random.normal(0, noise_level / 255.0, img.shape).astype( - np.float32 - ) + img += img * np.random.normal(0, noise_level / 255.0, img.shape).astype(np.float32) elif rnum < 0.4: - img += img * np.random.normal( - 0, noise_level / 255.0, (*img.shape[:2], 1) - ).astype(np.float32) + img += img * np.random.normal(0, noise_level / 255.0, (*img.shape[:2], 1)).astype(np.float32) else: L = noise_level2 / 255.0 D = np.diag(np.random.rand(3)) U = orth(np.random.rand(3, 3)) conv = np.dot(np.dot(np.transpose(U), D), U) - img += img * np.random.multivariate_normal( - [0, 0, 0], np.abs(L**2 * conv), img.shape[:2] - ).astype(np.float32) + img += img * np.random.multivariate_normal([0, 0, 0], np.abs(L**2 * conv), img.shape[:2]).astype(np.float32) img = np.clip(img, 0.0, 1.0) return img @@ -440,9 +426,7 @@ def add_Poisson_noise(img): else: img_gray = np.dot(img[..., :3], [0.299, 0.587, 0.114]) img_gray = np.clip((img_gray * 255.0).round(), 0, 255) / 255.0 - noise_gray = ( - np.random.poisson(img_gray * vals).astype(np.float32) / vals - img_gray - ) + noise_gray = np.random.poisson(img_gray * vals).astype(np.float32) / vals - img_gray img += noise_gray[:, :, np.newaxis] img = np.clip(img, 0.0, 1.0) return img @@ -451,9 +435,7 @@ def add_Poisson_noise(img): def add_JPEG_noise(img): quality_factor = random.randint(30, 95) img = cv2.cvtColor(util.single2uint(img), cv2.COLOR_RGB2BGR) - result, encimg = cv2.imencode( - ".jpg", img, [int(cv2.IMWRITE_JPEG_QUALITY), quality_factor] - ) + result, encimg = cv2.imencode(".jpg", img, [int(cv2.IMWRITE_JPEG_QUALITY), quality_factor]) img = cv2.imdecode(encimg, 1) img = cv2.cvtColor(util.uint2single(img), cv2.COLOR_BGR2RGB) return img @@ -540,9 +522,7 @@ def degradation_bsrgan(img, sf=4, lq_patchsize=72, isp_model=None): k = fspecial("gaussian", 25, random.uniform(0.1, 0.6 * sf)) k_shifted = shift_pixel(k, sf) k_shifted = k_shifted / k_shifted.sum() # blur with shifted kernel - img = ndimage.filters.convolve( - img, np.expand_dims(k_shifted, axis=2), mode="mirror" - ) + img = ndimage.filters.convolve(img, np.expand_dims(k_shifted, axis=2), mode="mirror") img = img[0::sf, 0::sf, ...] # nearest downsampling img = np.clip(img, 0.0, 1.0) @@ -646,9 +626,7 @@ def degradation_bsrgan_variant(image, sf=4, isp_model=None): k = fspecial("gaussian", 25, random.uniform(0.1, 0.6 * sf)) k_shifted = shift_pixel(k, sf) k_shifted = k_shifted / k_shifted.sum() # blur with shifted kernel - image = ndimage.filters.convolve( - image, np.expand_dims(k_shifted, axis=2), mode="mirror" - ) + image = ndimage.filters.convolve(image, np.expand_dims(k_shifted, axis=2), mode="mirror") image = image[0::sf, 0::sf, ...] # nearest downsampling image = np.clip(image, 0.0, 1.0) @@ -796,9 +774,7 @@ if __name__ == "__main__": print(i) img_lq = deg_fn(img) print(img_lq) - img_lq_bicubic = albumentations.SmallestMaxSize( - max_size=h, interpolation=cv2.INTER_CUBIC - )(image=img)["image"] + img_lq_bicubic = albumentations.SmallestMaxSize(max_size=h, interpolation=cv2.INTER_CUBIC)(image=img)["image"] print(img_lq.shape) print("bicubic", img_lq_bicubic.shape) print(img_hq.shape) @@ -812,7 +788,5 @@ if __name__ == "__main__": (int(sf * img_lq.shape[1]), int(sf * img_lq.shape[0])), interpolation=0, ) - img_concat = np.concatenate( - [lq_bicubic_nearest, lq_nearest, util.single2uint(img_hq)], axis=1 - ) + img_concat = np.concatenate([lq_bicubic_nearest, lq_nearest, util.single2uint(img_hq)], axis=1) util.imsave(img_concat, str(i) + ".png") diff --git a/invokeai/backend/stable_diffusion/image_degradation/bsrgan_light.py b/invokeai/backend/stable_diffusion/image_degradation/bsrgan_light.py index 1e8eee82b5..d0e0abadbc 100644 --- a/invokeai/backend/stable_diffusion/image_degradation/bsrgan_light.py +++ b/invokeai/backend/stable_diffusion/image_degradation/bsrgan_light.py @@ -261,9 +261,7 @@ def srmd_degradation(x, k, sf=3): year={2018} } """ - x = ndimage.filters.convolve( - x, np.expand_dims(k, axis=2), mode="wrap" - ) # 'nearest' | 'mirror' + x = ndimage.filters.convolve(x, np.expand_dims(k, axis=2), mode="wrap") # 'nearest' | 'mirror' x = bicubic_degradation(x, sf=sf) return x @@ -393,21 +391,15 @@ def add_Gaussian_noise(img, noise_level1=2, noise_level2=25): noise_level = random.randint(noise_level1, noise_level2) rnum = np.random.rand() if rnum > 0.6: # add color Gaussian noise - img = img + np.random.normal(0, noise_level / 255.0, img.shape).astype( - np.float32 - ) + img = img + np.random.normal(0, noise_level / 255.0, img.shape).astype(np.float32) elif rnum < 0.4: # add grayscale Gaussian noise - img = img + np.random.normal( - 0, noise_level / 255.0, (*img.shape[:2], 1) - ).astype(np.float32) + img = img + np.random.normal(0, noise_level / 255.0, (*img.shape[:2], 1)).astype(np.float32) else: # add noise L = noise_level2 / 255.0 D = np.diag(np.random.rand(3)) U = orth(np.random.rand(3, 3)) conv = np.dot(np.dot(np.transpose(U), D), U) - img = img + np.random.multivariate_normal( - [0, 0, 0], np.abs(L**2 * conv), img.shape[:2] - ).astype(np.float32) + img = img + np.random.multivariate_normal([0, 0, 0], np.abs(L**2 * conv), img.shape[:2]).astype(np.float32) img = np.clip(img, 0.0, 1.0) return img @@ -417,21 +409,15 @@ def add_speckle_noise(img, noise_level1=2, noise_level2=25): img = np.clip(img, 0.0, 1.0) rnum = random.random() if rnum > 0.6: - img += img * np.random.normal(0, noise_level / 255.0, img.shape).astype( - np.float32 - ) + img += img * np.random.normal(0, noise_level / 255.0, img.shape).astype(np.float32) elif rnum < 0.4: - img += img * np.random.normal( - 0, noise_level / 255.0, (*img.shape[:2], 1) - ).astype(np.float32) + img += img * np.random.normal(0, noise_level / 255.0, (*img.shape[:2], 1)).astype(np.float32) else: L = noise_level2 / 255.0 D = np.diag(np.random.rand(3)) U = orth(np.random.rand(3, 3)) conv = np.dot(np.dot(np.transpose(U), D), U) - img += img * np.random.multivariate_normal( - [0, 0, 0], np.abs(L**2 * conv), img.shape[:2] - ).astype(np.float32) + img += img * np.random.multivariate_normal([0, 0, 0], np.abs(L**2 * conv), img.shape[:2]).astype(np.float32) img = np.clip(img, 0.0, 1.0) return img @@ -444,9 +430,7 @@ def add_Poisson_noise(img): else: img_gray = np.dot(img[..., :3], [0.299, 0.587, 0.114]) img_gray = np.clip((img_gray * 255.0).round(), 0, 255) / 255.0 - noise_gray = ( - np.random.poisson(img_gray * vals).astype(np.float32) / vals - img_gray - ) + noise_gray = np.random.poisson(img_gray * vals).astype(np.float32) / vals - img_gray img += noise_gray[:, :, np.newaxis] img = np.clip(img, 0.0, 1.0) return img @@ -455,9 +439,7 @@ def add_Poisson_noise(img): def add_JPEG_noise(img): quality_factor = random.randint(80, 95) img = cv2.cvtColor(util.single2uint(img), cv2.COLOR_RGB2BGR) - result, encimg = cv2.imencode( - ".jpg", img, [int(cv2.IMWRITE_JPEG_QUALITY), quality_factor] - ) + result, encimg = cv2.imencode(".jpg", img, [int(cv2.IMWRITE_JPEG_QUALITY), quality_factor]) img = cv2.imdecode(encimg, 1) img = cv2.cvtColor(util.uint2single(img), cv2.COLOR_BGR2RGB) return img @@ -544,9 +526,7 @@ def degradation_bsrgan(img, sf=4, lq_patchsize=72, isp_model=None): k = fspecial("gaussian", 25, random.uniform(0.1, 0.6 * sf)) k_shifted = shift_pixel(k, sf) k_shifted = k_shifted / k_shifted.sum() # blur with shifted kernel - img = ndimage.filters.convolve( - img, np.expand_dims(k_shifted, axis=2), mode="mirror" - ) + img = ndimage.filters.convolve(img, np.expand_dims(k_shifted, axis=2), mode="mirror") img = img[0::sf, 0::sf, ...] # nearest downsampling img = np.clip(img, 0.0, 1.0) @@ -653,9 +633,7 @@ def degradation_bsrgan_variant(image, sf=4, isp_model=None): k = fspecial("gaussian", 25, random.uniform(0.1, 0.6 * sf)) k_shifted = shift_pixel(k, sf) k_shifted = k_shifted / k_shifted.sum() # blur with shifted kernel - image = ndimage.filters.convolve( - image, np.expand_dims(k_shifted, axis=2), mode="mirror" - ) + image = ndimage.filters.convolve(image, np.expand_dims(k_shifted, axis=2), mode="mirror") image = image[0::sf, 0::sf, ...] # nearest downsampling image = np.clip(image, 0.0, 1.0) @@ -705,9 +683,9 @@ if __name__ == "__main__": img_lq = deg_fn(img)["image"] img_hq, img_lq = util.uint2single(img_hq), util.uint2single(img_lq) print(img_lq) - img_lq_bicubic = albumentations.SmallestMaxSize( - max_size=h, interpolation=cv2.INTER_CUBIC - )(image=img_hq)["image"] + img_lq_bicubic = albumentations.SmallestMaxSize(max_size=h, interpolation=cv2.INTER_CUBIC)(image=img_hq)[ + "image" + ] print(img_lq.shape) print("bicubic", img_lq_bicubic.shape) print(img_hq.shape) @@ -721,7 +699,5 @@ if __name__ == "__main__": (int(sf * img_lq.shape[1]), int(sf * img_lq.shape[0])), interpolation=0, ) - img_concat = np.concatenate( - [lq_bicubic_nearest, lq_nearest, util.single2uint(img_hq)], axis=1 - ) + img_concat = np.concatenate([lq_bicubic_nearest, lq_nearest, util.single2uint(img_hq)], axis=1) util.imsave(img_concat, str(i) + ".png") diff --git a/invokeai/backend/stable_diffusion/image_degradation/utils_image.py b/invokeai/backend/stable_diffusion/image_degradation/utils_image.py index c4d37a24bf..d45ca602e6 100644 --- a/invokeai/backend/stable_diffusion/image_degradation/utils_image.py +++ b/invokeai/backend/stable_diffusion/image_degradation/utils_image.py @@ -11,6 +11,7 @@ from torchvision.utils import make_grid # import matplotlib.pyplot as plt # TODO: check with Dominik, also bsrgan.py vs bsrgan_light.py import invokeai.backend.util.logging as logger + os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" @@ -296,22 +297,14 @@ def single2uint16(img): def uint2tensor4(img): if img.ndim == 2: img = np.expand_dims(img, axis=2) - return ( - torch.from_numpy(np.ascontiguousarray(img)) - .permute(2, 0, 1) - .float() - .div(255.0) - .unsqueeze(0) - ) + return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float().div(255.0).unsqueeze(0) # convert uint to 3-dimensional torch tensor def uint2tensor3(img): if img.ndim == 2: img = np.expand_dims(img, axis=2) - return ( - torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float().div(255.0) - ) + return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float().div(255.0) # convert 2/3/4-dimensional torch tensor to uint @@ -334,12 +327,7 @@ def single2tensor3(img): # convert single (HxWxC) to 4-dimensional torch tensor def single2tensor4(img): - return ( - torch.from_numpy(np.ascontiguousarray(img)) - .permute(2, 0, 1) - .float() - .unsqueeze(0) - ) + return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float().unsqueeze(0) # convert torch tensor to single @@ -362,12 +350,7 @@ def tensor2single3(img): def single2tensor5(img): - return ( - torch.from_numpy(np.ascontiguousarray(img)) - .permute(2, 0, 1, 3) - .float() - .unsqueeze(0) - ) + return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1, 3).float().unsqueeze(0) def single32tensor5(img): @@ -385,9 +368,7 @@ def tensor2img(tensor, out_type=np.uint8, min_max=(0, 1)): Input: 4D(B,(3/1),H,W), 3D(C,H,W), or 2D(H,W), any range, RGB channel order Output: 3D(H,W,C) or 2D(H,W), [0,255], np.uint8 (default) """ - tensor = ( - tensor.squeeze().float().cpu().clamp_(*min_max) - ) # squeeze first, then clamp + tensor = tensor.squeeze().float().cpu().clamp_(*min_max) # squeeze first, then clamp tensor = (tensor - min_max[0]) / (min_max[1] - min_max[0]) # to range [0,1] n_dim = tensor.dim() if n_dim == 4: @@ -400,11 +381,7 @@ def tensor2img(tensor, out_type=np.uint8, min_max=(0, 1)): elif n_dim == 2: img_np = tensor.numpy() else: - raise TypeError( - "Only support 4D, 3D and 2D tensor. But received with dimension: {:d}".format( - n_dim - ) - ) + raise TypeError("Only support 4D, 3D and 2D tensor. But received with dimension: {:d}".format(n_dim)) if out_type == np.uint8: img_np = (img_np * 255.0).round() # Important. Unlike matlab, numpy.unit8() WILL NOT round by default. @@ -744,9 +721,7 @@ def ssim(img1, img2): sigma2_sq = cv2.filter2D(img2**2, -1, window)[5:-5, 5:-5] - mu2_sq sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2 - ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ( - (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2) - ) + ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)) return ssim_map.mean() @@ -767,9 +742,7 @@ def cubic(x): ) * (((absx > 1) * (absx <= 2)).type_as(absx)) -def calculate_weights_indices( - in_length, out_length, scale, kernel, kernel_width, antialiasing -): +def calculate_weights_indices(in_length, out_length, scale, kernel, kernel_width, antialiasing): if (scale < 1) and (antialiasing): # Use a modified kernel to simultaneously interpolate and antialias- larger kernel width kernel_width = kernel_width / scale @@ -793,9 +766,9 @@ def calculate_weights_indices( # The indices of the input pixels involved in computing the k-th output # pixel are in row k of the indices matrix. - indices = left.view(out_length, 1).expand(out_length, P) + torch.linspace( - 0, P - 1, P - ).view(1, P).expand(out_length, P) + indices = left.view(out_length, 1).expand(out_length, P) + torch.linspace(0, P - 1, P).view(1, P).expand( + out_length, P + ) # The weights used to compute the k-th output pixel are in row k of the # weights matrix. @@ -876,9 +849,7 @@ def imresize(img, scale, antialiasing=True): for i in range(out_H): idx = int(indices_H[i][0]) for j in range(out_C): - out_1[j, i, :] = ( - img_aug[j, idx : idx + kernel_width, :].transpose(0, 1).mv(weights_H[i]) - ) + out_1[j, i, :] = img_aug[j, idx : idx + kernel_width, :].transpose(0, 1).mv(weights_H[i]) # process W dimension # symmetric copying @@ -959,9 +930,7 @@ def imresize_np(img, scale, antialiasing=True): for i in range(out_H): idx = int(indices_H[i][0]) for j in range(out_C): - out_1[i, :, j] = ( - img_aug[idx : idx + kernel_width, :, j].transpose(0, 1).mv(weights_H[i]) - ) + out_1[i, :, j] = img_aug[idx : idx + kernel_width, :, j].transpose(0, 1).mv(weights_H[i]) # process W dimension # symmetric copying diff --git a/invokeai/backend/stable_diffusion/offloading.py b/invokeai/backend/stable_diffusion/offloading.py index d36b65872a..aa2426d514 100644 --- a/invokeai/backend/stable_diffusion/offloading.py +++ b/invokeai/backend/stable_diffusion/offloading.py @@ -95,10 +95,7 @@ class ModelGroup(metaclass=ABCMeta): pass def __repr__(self) -> str: - return ( - f"<{self.__class__.__name__} object at {id(self):x}: " - f"device={self.execution_device} >" - ) + return f"<{self.__class__.__name__} object at {id(self):x}: " f"device={self.execution_device} >" class LazilyLoadedModelGroup(ModelGroup): @@ -143,8 +140,7 @@ class LazilyLoadedModelGroup(ModelGroup): self.load(module) if len(forward_input) == 0: warnings.warn( - f"Hook for {module.__class__.__name__} got no input. " - f"Inputs must be positional, not keywords.", + f"Hook for {module.__class__.__name__} got no input. " f"Inputs must be positional, not keywords.", stacklevel=3, ) return send_to_device(forward_input, self.execution_device) @@ -161,9 +157,7 @@ class LazilyLoadedModelGroup(ModelGroup): self.clear_current_model() def _load(self, module: torch.nn.Module) -> torch.nn.Module: - assert ( - self.is_empty() - ), f"A model is already loaded: {self._current_model_ref()}" + assert self.is_empty(), f"A model is already loaded: {self._current_model_ref()}" module = module.to(self.execution_device) self.set_current_model(module) return module @@ -192,12 +186,8 @@ class LazilyLoadedModelGroup(ModelGroup): def device_for(self, model): if model not in self: - raise KeyError( - f"This does not manage this model {type(model).__name__}", model - ) - return ( - self.execution_device - ) # this implementation only dispatches to one device + raise KeyError(f"This does not manage this model {type(model).__name__}", model) + return self.execution_device # this implementation only dispatches to one device def ready(self): pass # always ready to load on-demand @@ -256,12 +246,8 @@ class FullyLoadedModelGroup(ModelGroup): def device_for(self, model): if model not in self: - raise KeyError( - "This does not manage this model f{type(model).__name__}", model - ) - return ( - self.execution_device - ) # this implementation only dispatches to one device + raise KeyError("This does not manage this model f{type(model).__name__}", model) + return self.execution_device # this implementation only dispatches to one device def __contains__(self, model): return model in self._models diff --git a/invokeai/backend/stable_diffusion/schedulers/__init__.py b/invokeai/backend/stable_diffusion/schedulers/__init__.py index b2df0df231..29a96eb3a5 100644 --- a/invokeai/backend/stable_diffusion/schedulers/__init__.py +++ b/invokeai/backend/stable_diffusion/schedulers/__init__.py @@ -1 +1 @@ -from .schedulers import SCHEDULER_MAP \ No newline at end of file +from .schedulers import SCHEDULER_MAP diff --git a/invokeai/backend/stable_diffusion/schedulers/schedulers.py b/invokeai/backend/stable_diffusion/schedulers/schedulers.py index 77c45d5eb8..2f62f8c477 100644 --- a/invokeai/backend/stable_diffusion/schedulers/schedulers.py +++ b/invokeai/backend/stable_diffusion/schedulers/schedulers.py @@ -1,7 +1,19 @@ -from diffusers import DDIMScheduler, DPMSolverMultistepScheduler, KDPM2DiscreteScheduler, \ - KDPM2AncestralDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, \ - HeunDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, UniPCMultistepScheduler, \ - DPMSolverSinglestepScheduler, DEISMultistepScheduler, DDPMScheduler, DPMSolverSDEScheduler +from diffusers import ( + DDIMScheduler, + DPMSolverMultistepScheduler, + KDPM2DiscreteScheduler, + KDPM2AncestralDiscreteScheduler, + EulerDiscreteScheduler, + EulerAncestralDiscreteScheduler, + HeunDiscreteScheduler, + LMSDiscreteScheduler, + PNDMScheduler, + UniPCMultistepScheduler, + DPMSolverSinglestepScheduler, + DEISMultistepScheduler, + DDPMScheduler, + DPMSolverSDEScheduler, +) SCHEDULER_MAP = dict( ddim=(DDIMScheduler, dict()), @@ -21,9 +33,9 @@ SCHEDULER_MAP = dict( dpmpp_2s_k=(DPMSolverSinglestepScheduler, dict(use_karras_sigmas=True)), dpmpp_2m=(DPMSolverMultistepScheduler, dict(use_karras_sigmas=False)), dpmpp_2m_k=(DPMSolverMultistepScheduler, dict(use_karras_sigmas=True)), - dpmpp_2m_sde=(DPMSolverMultistepScheduler, dict(use_karras_sigmas=False, algorithm_type='sde-dpmsolver++')), - dpmpp_2m_sde_k=(DPMSolverMultistepScheduler, dict(use_karras_sigmas=True, algorithm_type='sde-dpmsolver++')), + dpmpp_2m_sde=(DPMSolverMultistepScheduler, dict(use_karras_sigmas=False, algorithm_type="sde-dpmsolver++")), + dpmpp_2m_sde_k=(DPMSolverMultistepScheduler, dict(use_karras_sigmas=True, algorithm_type="sde-dpmsolver++")), dpmpp_sde=(DPMSolverSDEScheduler, dict(use_karras_sigmas=False, noise_sampler_seed=0)), dpmpp_sde_k=(DPMSolverSDEScheduler, dict(use_karras_sigmas=True, noise_sampler_seed=0)), - unipc=(UniPCMultistepScheduler, dict(cpu_only=True)) + unipc=(UniPCMultistepScheduler, dict(cpu_only=True)), ) diff --git a/invokeai/backend/training/textual_inversion_training.py b/invokeai/backend/training/textual_inversion_training.py index aadf8c76a3..d92aa80b38 100644 --- a/invokeai/backend/training/textual_inversion_training.py +++ b/invokeai/backend/training/textual_inversion_training.py @@ -45,7 +45,7 @@ from tqdm.auto import tqdm from transformers import CLIPTextModel, CLIPTokenizer # invokeai stuff -from invokeai.app.services.config import InvokeAIAppConfig,PagingArgumentParser +from invokeai.app.services.config import InvokeAIAppConfig, PagingArgumentParser from invokeai.app.services.model_manager_service import ModelManagerService from invokeai.backend.model_management.models import SubModelType @@ -75,24 +75,16 @@ check_min_version("0.10.0.dev0") logger = get_logger(__name__) -def save_progress( - text_encoder, placeholder_token_id, accelerator, placeholder_token, save_path -): +def save_progress(text_encoder, placeholder_token_id, accelerator, placeholder_token, save_path): logger.info("Saving embeddings") - learned_embeds = ( - accelerator.unwrap_model(text_encoder) - .get_input_embeddings() - .weight[placeholder_token_id] - ) + learned_embeds = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[placeholder_token_id] learned_embeds_dict = {placeholder_token: learned_embeds.detach().cpu()} torch.save(learned_embeds_dict, save_path) def parse_args(): config = InvokeAIAppConfig.get_config() - parser = PagingArgumentParser( - description="Textual inversion training" - ) + parser = PagingArgumentParser(description="Textual inversion training") general_group = parser.add_argument_group("General") model_group = parser.add_argument_group("Models and Paths") image_group = parser.add_argument_group("Training Image Location and Options") @@ -221,9 +213,7 @@ def parse_args(): default=100, help="How many times to repeat the training data.", ) - training_group.add_argument( - "--seed", type=int, default=None, help="A seed for reproducible training." - ) + training_group.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.") training_group.add_argument( "--train_batch_size", type=int, @@ -287,9 +277,7 @@ def parse_args(): default=0.999, help="The beta2 parameter for the Adam optimizer.", ) - training_group.add_argument( - "--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use." - ) + training_group.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.") training_group.add_argument( "--adam_epsilon", type=float, @@ -442,9 +430,7 @@ class TextualInversionDataset(Dataset): self.data_root / file_path for file_path in self.data_root.iterdir() if file_path.is_file() - and file_path.name.endswith( - (".png", ".PNG", ".jpg", ".JPG", ".jpeg", ".JPEG", ".gif", ".GIF") - ) + and file_path.name.endswith((".png", ".PNG", ".jpg", ".JPG", ".jpeg", ".JPEG", ".gif", ".GIF")) ] self.num_images = len(self.image_paths) @@ -460,11 +446,7 @@ class TextualInversionDataset(Dataset): "lanczos": PIL_INTERPOLATION["lanczos"], }[interpolation] - self.templates = ( - imagenet_style_templates_small - if learnable_property == "style" - else imagenet_templates_small - ) + self.templates = imagenet_style_templates_small if learnable_property == "style" else imagenet_templates_small self.flip_transform = transforms.RandomHorizontalFlip(p=self.flip_p) def __len__(self): @@ -500,9 +482,7 @@ class TextualInversionDataset(Dataset): img.shape[0], img.shape[1], ) - img = img[ - (h - crop) // 2 : (h + crop) // 2, (w - crop) // 2 : (w + crop) // 2 - ] + img = img[(h - crop) // 2 : (h + crop) // 2, (w - crop) // 2 : (w + crop) // 2] image = Image.fromarray(img) image = image.resize((self.size, self.size), resample=self.interpolation) @@ -515,9 +495,7 @@ class TextualInversionDataset(Dataset): return example -def get_full_repo_name( - model_id: str, organization: Optional[str] = None, token: Optional[str] = None -): +def get_full_repo_name(model_id: str, organization: Optional[str] = None, token: Optional[str] = None): if token is None: token = HfFolder.get_token() if organization is None: @@ -570,9 +548,7 @@ def do_textual_inversion_training( **kwargs, ): assert model, "Please specify a base model with --model" - assert ( - train_data_dir - ), "Please specify a directory containing the training images using --train_data_dir" + assert train_data_dir, "Please specify a directory containing the training images using --train_data_dir" assert placeholder_token, "Please specify a trigger term using --placeholder_token" env_local_rank = int(os.environ.get("LOCAL_RANK", -1)) if env_local_rank != -1 and env_local_rank != local_rank: @@ -593,7 +569,7 @@ def do_textual_inversion_training( project_config=accelerator_config, ) - model_manager = ModelManagerService(config,logger) + model_manager = ModelManagerService(config, logger) # Make one log on every process with the configuration for debugging. logging.basicConfig( @@ -633,13 +609,11 @@ def do_textual_inversion_training( os.makedirs(output_dir, exist_ok=True) known_models = model_manager.model_names() - model_name = model.split('/')[-1] + model_name = model.split("/")[-1] model_meta = next((mm for mm in known_models if mm[0].endswith(model_name)), None) assert model_meta is not None, f"Unknown model: {model}" model_info = model_manager.model_info(*model_meta) - assert ( - model_info['model_format'] == "diffusers" - ), "This script only works with models of type 'diffusers'" + assert model_info["model_format"] == "diffusers", "This script only works with models of type 'diffusers'" tokenizer_info = model_manager.get_model(*model_meta, submodel=SubModelType.Tokenizer) noise_scheduler_info = model_manager.get_model(*model_meta, submodel=SubModelType.Scheduler) text_encoder_info = model_manager.get_model(*model_meta, submodel=SubModelType.TextEncoder) @@ -650,9 +624,7 @@ def do_textual_inversion_training( if tokenizer_name: tokenizer = CLIPTokenizer.from_pretrained(tokenizer_name, **pipeline_args) else: - tokenizer = CLIPTokenizer.from_pretrained( - tokenizer_info.location, subfolder='tokenizer', **pipeline_args - ) + tokenizer = CLIPTokenizer.from_pretrained(tokenizer_info.location, subfolder="tokenizer", **pipeline_args) # Load scheduler and models noise_scheduler = DDPMScheduler.from_pretrained( @@ -722,9 +694,7 @@ def do_textual_inversion_training( if is_xformers_available(): unet.enable_xformers_memory_efficient_attention() else: - raise ValueError( - "xformers is not available. Make sure it is installed correctly" - ) + raise ValueError("xformers is not available. Make sure it is installed correctly") # Enable TF32 for faster training on Ampere GPUs, # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices @@ -732,12 +702,7 @@ def do_textual_inversion_training( torch.backends.cuda.matmul.allow_tf32 = True if scale_lr: - learning_rate = ( - learning_rate - * gradient_accumulation_steps - * train_batch_size - * accelerator.num_processes - ) + learning_rate = learning_rate * gradient_accumulation_steps * train_batch_size * accelerator.num_processes # Initialize the optimizer optimizer = torch.optim.AdamW( @@ -759,15 +724,11 @@ def do_textual_inversion_training( center_crop=center_crop, set="train", ) - train_dataloader = torch.utils.data.DataLoader( - train_dataset, batch_size=train_batch_size, shuffle=True - ) + train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=train_batch_size, shuffle=True) # Scheduler and math around the number of training steps. overrode_max_train_steps = False - num_update_steps_per_epoch = math.ceil( - len(train_dataloader) / gradient_accumulation_steps - ) + num_update_steps_per_epoch = math.ceil(len(train_dataloader) / gradient_accumulation_steps) if max_train_steps is None: max_train_steps = num_train_epochs * num_update_steps_per_epoch overrode_max_train_steps = True @@ -797,9 +758,7 @@ def do_textual_inversion_training( vae.to(accelerator.device, dtype=weight_dtype) # We need to recalculate our total training steps as the size of the training dataloader may have changed. - num_update_steps_per_epoch = math.ceil( - len(train_dataloader) / gradient_accumulation_steps - ) + num_update_steps_per_epoch = math.ceil(len(train_dataloader) / gradient_accumulation_steps) if overrode_max_train_steps: max_train_steps = num_train_epochs * num_update_steps_per_epoch # Afterwards we recalculate our number of training epochs @@ -814,17 +773,13 @@ def do_textual_inversion_training( accelerator.init_trackers("textual_inversion", config=params) # Train! - total_batch_size = ( - train_batch_size * accelerator.num_processes * gradient_accumulation_steps - ) + total_batch_size = train_batch_size * accelerator.num_processes * gradient_accumulation_steps logger.info("***** Running training *****") logger.info(f" Num examples = {len(train_dataset)}") logger.info(f" Num Epochs = {num_train_epochs}") logger.info(f" Instantaneous batch size per device = {train_batch_size}") - logger.info( - f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}" - ) + logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}") logger.info(f" Gradient Accumulation steps = {gradient_accumulation_steps}") logger.info(f" Total optimization steps = {max_train_steps}") global_step = 0 @@ -843,9 +798,7 @@ def do_textual_inversion_training( path = dirs[-1] if len(dirs) > 0 else None if path is None: - accelerator.print( - f"Checkpoint '{resume_from_checkpoint}' does not exist. Starting a new training run." - ) + accelerator.print(f"Checkpoint '{resume_from_checkpoint}' does not exist. Starting a new training run.") resume_from_checkpoint = None else: accelerator.print(f"Resuming from checkpoint {path}") @@ -854,9 +807,7 @@ def do_textual_inversion_training( resume_global_step = global_step * gradient_accumulation_steps first_epoch = global_step // num_update_steps_per_epoch - resume_step = resume_global_step % ( - num_update_steps_per_epoch * gradient_accumulation_steps - ) + resume_step = resume_global_step % (num_update_steps_per_epoch * gradient_accumulation_steps) # Only show the progress bar once on each machine. progress_bar = tqdm( @@ -866,33 +817,20 @@ def do_textual_inversion_training( progress_bar.set_description("Steps") # keep original embeddings as reference - orig_embeds_params = ( - accelerator.unwrap_model(text_encoder) - .get_input_embeddings() - .weight.data.clone() - ) + orig_embeds_params = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight.data.clone() for epoch in range(first_epoch, num_train_epochs): text_encoder.train() for step, batch in enumerate(train_dataloader): # Skip steps until we reach the resumed step - if ( - resume_step - and resume_from_checkpoint - and epoch == first_epoch - and step < resume_step - ): + if resume_step and resume_from_checkpoint and epoch == first_epoch and step < resume_step: if step % gradient_accumulation_steps == 0: progress_bar.update(1) continue with accelerator.accumulate(text_encoder): # Convert images to latent space - latents = ( - vae.encode(batch["pixel_values"].to(dtype=weight_dtype)) - .latent_dist.sample() - .detach() - ) + latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample().detach() latents = latents * 0.18215 # Sample noise that we'll add to the latents @@ -912,14 +850,10 @@ def do_textual_inversion_training( noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps) # Get the text embedding for conditioning - encoder_hidden_states = text_encoder(batch["input_ids"])[0].to( - dtype=weight_dtype - ) + encoder_hidden_states = text_encoder(batch["input_ids"])[0].to(dtype=weight_dtype) # Predict the noise residual - model_pred = unet( - noisy_latents, timesteps, encoder_hidden_states - ).sample + model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample # Get the target for loss depending on the prediction type if noise_scheduler.config.prediction_type == "epsilon": @@ -927,9 +861,7 @@ def do_textual_inversion_training( elif noise_scheduler.config.prediction_type == "v_prediction": target = noise_scheduler.get_velocity(latents, noise, timesteps) else: - raise ValueError( - f"Unknown prediction type {noise_scheduler.config.prediction_type}" - ) + raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}") loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean") @@ -942,22 +874,16 @@ def do_textual_inversion_training( # Let's make sure we don't update any embedding weights besides the newly added token index_no_updates = torch.arange(len(tokenizer)) != placeholder_token_id with torch.no_grad(): - accelerator.unwrap_model( - text_encoder - ).get_input_embeddings().weight[ + accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[ index_no_updates - ] = orig_embeds_params[ - index_no_updates - ] + ] = orig_embeds_params[index_no_updates] # Checks if the accelerator has performed an optimization step behind the scenes if accelerator.sync_gradients: progress_bar.update(1) global_step += 1 if global_step % save_steps == 0: - save_path = os.path.join( - output_dir, f"learned_embeds-steps-{global_step}.bin" - ) + save_path = os.path.join(output_dir, f"learned_embeds-steps-{global_step}.bin") save_progress( text_encoder, placeholder_token_id, @@ -968,9 +894,7 @@ def do_textual_inversion_training( if global_step % checkpointing_steps == 0: if accelerator.is_main_process: - save_path = os.path.join( - output_dir, f"checkpoint-{global_step}" - ) + save_path = os.path.join(output_dir, f"checkpoint-{global_step}") accelerator.save_state(save_path) logger.info(f"Saved state to {save_path}") @@ -985,9 +909,7 @@ def do_textual_inversion_training( accelerator.wait_for_everyone() if accelerator.is_main_process: if push_to_hub and only_save_embeds: - logger.warn( - "Enabling full model saving because --push_to_hub=True was specified." - ) + logger.warn("Enabling full model saving because --push_to_hub=True was specified.") save_full_model = True else: save_full_model = not only_save_embeds @@ -1012,8 +934,6 @@ def do_textual_inversion_training( ) if push_to_hub: - repo.push_to_hub( - commit_message="End of training", blocking=False, auto_lfs_prune=True - ) + repo.push_to_hub(commit_message="End of training", blocking=False, auto_lfs_prune=True) accelerator.end_training() diff --git a/invokeai/backend/util/__init__.py b/invokeai/backend/util/__init__.py index fadeff4d75..2e69af5382 100644 --- a/invokeai/backend/util/__init__.py +++ b/invokeai/backend/util/__init__.py @@ -11,12 +11,4 @@ from .devices import ( torch_dtype, ) from .log import write_log -from .util import ( - ask_user, - download_with_resume, - instantiate_from_config, - url_attachment_name, - Chdir -) - - +from .util import ask_user, download_with_resume, instantiate_from_config, url_attachment_name, Chdir diff --git a/invokeai/backend/util/devices.py b/invokeai/backend/util/devices.py index 3fbdaba41a..eeabcc35db 100644 --- a/invokeai/backend/util/devices.py +++ b/invokeai/backend/util/devices.py @@ -12,6 +12,7 @@ CUDA_DEVICE = torch.device("cuda") MPS_DEVICE = torch.device("mps") config = InvokeAIAppConfig.get_config() + def choose_torch_device() -> torch.device: """Convenience routine for guessing which GPU device to run model on""" if config.always_use_cpu: diff --git a/invokeai/backend/util/hotfixes.py b/invokeai/backend/util/hotfixes.py index 67e46a426f..4710682ac1 100644 --- a/invokeai/backend/util/hotfixes.py +++ b/invokeai/backend/util/hotfixes.py @@ -20,6 +20,7 @@ from diffusers.models.controlnet import ControlNetConditioningEmbedding, Control # Modified ControlNetModel with encoder_attention_mask argument added + class ControlNetModel(ModelMixin, ConfigMixin): """ A ControlNet model. @@ -618,9 +619,7 @@ class ControlNetModel(ModelMixin, ConfigMixin): mid_block_res_sample = mid_block_res_sample * conditioning_scale if self.config.global_pool_conditions: - down_block_res_samples = [ - torch.mean(sample, dim=(2, 3), keepdim=True) for sample in down_block_res_samples - ] + down_block_res_samples = [torch.mean(sample, dim=(2, 3), keepdim=True) for sample in down_block_res_samples] mid_block_res_sample = torch.mean(mid_block_res_sample, dim=(2, 3), keepdim=True) if not return_dict: @@ -630,5 +629,6 @@ class ControlNetModel(ModelMixin, ConfigMixin): down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample ) + diffusers.ControlNetModel = ControlNetModel -diffusers.models.controlnet.ControlNetModel = ControlNetModel \ No newline at end of file +diffusers.models.controlnet.ControlNetModel = ControlNetModel diff --git a/invokeai/backend/util/logging.py b/invokeai/backend/util/logging.py index d06c036506..3a8d721aa5 100644 --- a/invokeai/backend/util/logging.py +++ b/invokeai/backend/util/logging.py @@ -186,89 +186,109 @@ from invokeai.app.services.config import InvokeAIAppConfig, get_invokeai_config try: import syslog + SYSLOG_AVAILABLE = True except: SYSLOG_AVAILABLE = False + # module level functions def debug(msg, *args, **kwargs): InvokeAILogger.getLogger().debug(msg, *args, **kwargs) + def info(msg, *args, **kwargs): InvokeAILogger.getLogger().info(msg, *args, **kwargs) + def warning(msg, *args, **kwargs): InvokeAILogger.getLogger().warning(msg, *args, **kwargs) + def error(msg, *args, **kwargs): InvokeAILogger.getLogger().error(msg, *args, **kwargs) + def critical(msg, *args, **kwargs): InvokeAILogger.getLogger().critical(msg, *args, **kwargs) + def log(level, msg, *args, **kwargs): InvokeAILogger.getLogger().log(level, msg, *args, **kwargs) + def disable(level=logging.CRITICAL): InvokeAILogger.getLogger().disable(level) + def basicConfig(**kwargs): InvokeAILogger.getLogger().basicConfig(**kwargs) + def getLogger(name: str = None) -> logging.Logger: return InvokeAILogger.getLogger(name) -_FACILITY_MAP = dict( - LOG_KERN = syslog.LOG_KERN, - LOG_USER = syslog.LOG_USER, - LOG_MAIL = syslog.LOG_MAIL, - LOG_DAEMON = syslog.LOG_DAEMON, - LOG_AUTH = syslog.LOG_AUTH, - LOG_LPR = syslog.LOG_LPR, - LOG_NEWS = syslog.LOG_NEWS, - LOG_UUCP = syslog.LOG_UUCP, - LOG_CRON = syslog.LOG_CRON, - LOG_SYSLOG = syslog.LOG_SYSLOG, - LOG_LOCAL0 = syslog.LOG_LOCAL0, - LOG_LOCAL1 = syslog.LOG_LOCAL1, - LOG_LOCAL2 = syslog.LOG_LOCAL2, - LOG_LOCAL3 = syslog.LOG_LOCAL3, - LOG_LOCAL4 = syslog.LOG_LOCAL4, - LOG_LOCAL5 = syslog.LOG_LOCAL5, - LOG_LOCAL6 = syslog.LOG_LOCAL6, - LOG_LOCAL7 = syslog.LOG_LOCAL7, -) if SYSLOG_AVAILABLE else dict() - -_SOCK_MAP = dict( - SOCK_STREAM = socket.SOCK_STREAM, - SOCK_DGRAM = socket.SOCK_DGRAM, +_FACILITY_MAP = ( + dict( + LOG_KERN=syslog.LOG_KERN, + LOG_USER=syslog.LOG_USER, + LOG_MAIL=syslog.LOG_MAIL, + LOG_DAEMON=syslog.LOG_DAEMON, + LOG_AUTH=syslog.LOG_AUTH, + LOG_LPR=syslog.LOG_LPR, + LOG_NEWS=syslog.LOG_NEWS, + LOG_UUCP=syslog.LOG_UUCP, + LOG_CRON=syslog.LOG_CRON, + LOG_SYSLOG=syslog.LOG_SYSLOG, + LOG_LOCAL0=syslog.LOG_LOCAL0, + LOG_LOCAL1=syslog.LOG_LOCAL1, + LOG_LOCAL2=syslog.LOG_LOCAL2, + LOG_LOCAL3=syslog.LOG_LOCAL3, + LOG_LOCAL4=syslog.LOG_LOCAL4, + LOG_LOCAL5=syslog.LOG_LOCAL5, + LOG_LOCAL6=syslog.LOG_LOCAL6, + LOG_LOCAL7=syslog.LOG_LOCAL7, + ) + if SYSLOG_AVAILABLE + else dict() ) +_SOCK_MAP = dict( + SOCK_STREAM=socket.SOCK_STREAM, + SOCK_DGRAM=socket.SOCK_DGRAM, +) + + class InvokeAIFormatter(logging.Formatter): - ''' + """ Base class for logging formatter - ''' + """ + def format(self, record): formatter = logging.Formatter(self.log_fmt(record.levelno)) return formatter.format(record) @abstractmethod - def log_fmt(self, levelno: int)->str: + def log_fmt(self, levelno: int) -> str: pass - + + class InvokeAISyslogFormatter(InvokeAIFormatter): - ''' + """ Formatting for syslog - ''' - def log_fmt(self, levelno: int)->str: - return '%(name)s [%(process)d] <%(levelname)s> %(message)s' + """ + + def log_fmt(self, levelno: int) -> str: + return "%(name)s [%(process)d] <%(levelname)s> %(message)s" + class InvokeAILegacyLogFormatter(InvokeAIFormatter): - ''' + """ Formatting for the InvokeAI Logger (legacy version) - ''' + """ + FORMATS = { logging.DEBUG: " | %(message)s", logging.INFO: ">> %(message)s", @@ -276,20 +296,25 @@ class InvokeAILegacyLogFormatter(InvokeAIFormatter): logging.ERROR: "*** %(message)s", logging.CRITICAL: "### %(message)s", } - def log_fmt(self,levelno:int)->str: + + def log_fmt(self, levelno: int) -> str: return self.FORMATS.get(levelno) + class InvokeAIPlainLogFormatter(InvokeAIFormatter): - ''' + """ Custom Formatting for the InvokeAI Logger (plain version) - ''' - def log_fmt(self, levelno: int)->str: + """ + + def log_fmt(self, levelno: int) -> str: return "[%(asctime)s]::[%(name)s]::%(levelname)s --> %(message)s" + class InvokeAIColorLogFormatter(InvokeAIFormatter): - ''' + """ Custom Formatting for the InvokeAI Logger - ''' + """ + # Color Codes grey = "\x1b[38;20m" yellow = "\x1b[33;20m" @@ -308,32 +333,34 @@ class InvokeAIColorLogFormatter(InvokeAIFormatter): logging.INFO: grey + log_format + reset, logging.WARNING: yellow + log_format + reset, logging.ERROR: red + log_format + reset, - logging.CRITICAL: bold_red + log_format + reset + logging.CRITICAL: bold_red + log_format + reset, } - def log_fmt(self, levelno: int)->str: + def log_fmt(self, levelno: int) -> str: return self.FORMATS.get(levelno) + LOG_FORMATTERS = { - 'plain': InvokeAIPlainLogFormatter, - 'color': InvokeAIColorLogFormatter, - 'syslog': InvokeAISyslogFormatter, - 'legacy': InvokeAILegacyLogFormatter, + "plain": InvokeAIPlainLogFormatter, + "color": InvokeAIColorLogFormatter, + "syslog": InvokeAISyslogFormatter, + "legacy": InvokeAILegacyLogFormatter, } + class InvokeAILogger(object): loggers = dict() @classmethod - def getLogger(cls, - name: str = 'InvokeAI', - config: InvokeAIAppConfig=InvokeAIAppConfig.get_config())->logging.Logger: + def getLogger( + cls, name: str = "InvokeAI", config: InvokeAIAppConfig = InvokeAIAppConfig.get_config() + ) -> logging.Logger: if name in cls.loggers: logger = cls.loggers[name] logger.handlers.clear() else: logger = logging.getLogger(name) - logger.setLevel(config.log_level.upper()) # yes, strings work here + logger.setLevel(config.log_level.upper()) # yes, strings work here for ch in cls.getLoggers(config): logger.addHandler(ch) cls.loggers[name] = logger @@ -344,82 +371,80 @@ class InvokeAILogger(object): handler_strs = config.log_handlers handlers = list() for handler in handler_strs: - handler_name,*args = handler.split('=',2) + handler_name, *args = handler.split("=", 2) args = args[0] if len(args) > 0 else None # console and file get the fancy formatter. # syslog gets a simple one # http gets no custom formatter formatter = LOG_FORMATTERS[config.log_format] - if handler_name=='console': + if handler_name == "console": ch = logging.StreamHandler() ch.setFormatter(formatter()) handlers.append(ch) - - elif handler_name=='syslog': + + elif handler_name == "syslog": ch = cls._parse_syslog_args(args) handlers.append(ch) - - elif handler_name=='file': + + elif handler_name == "file": ch = cls._parse_file_args(args) ch.setFormatter(formatter()) handlers.append(ch) - - elif handler_name=='http': + + elif handler_name == "http": ch = cls._parse_http_args(args) handlers.append(ch) return handlers @staticmethod - def _parse_syslog_args( - args: str=None - )-> logging.Handler: + def _parse_syslog_args(args: str = None) -> logging.Handler: if not SYSLOG_AVAILABLE: raise ValueError("syslog is not available on this system") if not args: - args='/dev/log' if Path('/dev/log').exists() else 'address:localhost:514' + args = "/dev/log" if Path("/dev/log").exists() else "address:localhost:514" syslog_args = dict() try: - for a in args.split(','): - arg_name,*arg_value = a.split(':',2) - if arg_name=='address': - host,*port = arg_value - port = 514 if len(port)==0 else int(port[0]) - syslog_args['address'] = (host,port) - elif arg_name=='facility': - syslog_args['facility'] = _FACILITY_MAP[arg_value[0]] - elif arg_name=='socktype': - syslog_args['socktype'] = _SOCK_MAP[arg_value[0]] + for a in args.split(","): + arg_name, *arg_value = a.split(":", 2) + if arg_name == "address": + host, *port = arg_value + port = 514 if len(port) == 0 else int(port[0]) + syslog_args["address"] = (host, port) + elif arg_name == "facility": + syslog_args["facility"] = _FACILITY_MAP[arg_value[0]] + elif arg_name == "socktype": + syslog_args["socktype"] = _SOCK_MAP[arg_value[0]] else: - syslog_args['address'] = arg_name + syslog_args["address"] = arg_name except: raise ValueError(f"{args} is not a value argument list for syslog logging") return logging.handlers.SysLogHandler(**syslog_args) - + @staticmethod - def _parse_file_args(args: str=None)-> logging.Handler: + def _parse_file_args(args: str = None) -> logging.Handler: if not args: raise ValueError("please provide filename for file logging using format 'file=/path/to/logfile.txt'") return logging.FileHandler(args) @staticmethod - def _parse_http_args(args: str=None)-> logging.Handler: + def _parse_http_args(args: str = None) -> logging.Handler: if not args: raise ValueError("please provide destination for http logging using format 'http=url'") - arg_list = args.split(',') + arg_list = args.split(",") url = urllib.parse.urlparse(arg_list.pop(0)) - if url.scheme != 'http': + if url.scheme != "http": raise ValueError(f"the http logging module can only log to HTTP URLs, but {url.scheme} was specified") host = url.hostname path = url.path port = url.port or 80 - + syslog_args = dict() for a in arg_list: - arg_name, *arg_value = a.split(':',2) - if arg_name=='method': - arg_value = arg_value[0] if len(arg_value)>0 else 'GET' + arg_name, *arg_value = a.split(":", 2) + if arg_name == "method": + arg_value = arg_value[0] if len(arg_value) > 0 else "GET" syslog_args[arg_name] = arg_value else: # TODO: Provide support for SSL context and credentials pass - return logging.handlers.HTTPHandler(f'{host}:{port}',path,**syslog_args) + return logging.handlers.HTTPHandler(f"{host}:{port}", path, **syslog_args) diff --git a/invokeai/backend/util/mps_fixes.py b/invokeai/backend/util/mps_fixes.py index e4d8da20a9..409eff1c8b 100644 --- a/invokeai/backend/util/mps_fixes.py +++ b/invokeai/backend/util/mps_fixes.py @@ -8,6 +8,8 @@ if torch.backends.mps.is_available(): _torch_layer_norm = torch.nn.functional.layer_norm + + def new_layer_norm(input, normalized_shape, weight=None, bias=None, eps=1e-05): if input.device.type == "mps" and input.dtype == torch.float16: input = input.float() @@ -19,20 +21,26 @@ def new_layer_norm(input, normalized_shape, weight=None, bias=None, eps=1e-05): else: return _torch_layer_norm(input, normalized_shape, weight, bias, eps) + torch.nn.functional.layer_norm = new_layer_norm _torch_tensor_permute = torch.Tensor.permute + + def new_torch_tensor_permute(input, *dims): result = _torch_tensor_permute(input, *dims) if input.device == "mps" and input.dtype == torch.float16: result = result.contiguous() return result + torch.Tensor.permute = new_torch_tensor_permute _torch_lerp = torch.lerp + + def new_torch_lerp(input, end, weight, *, out=None): if input.device.type == "mps" and input.dtype == torch.float16: input = input.float() @@ -52,20 +60,36 @@ def new_torch_lerp(input, end, weight, *, out=None): else: return _torch_lerp(input, end, weight, out=out) + torch.lerp = new_torch_lerp _torch_interpolate = torch.nn.functional.interpolate -def new_torch_interpolate(input, size=None, scale_factor=None, mode='nearest', align_corners=None, recompute_scale_factor=None, antialias=False): + + +def new_torch_interpolate( + input, + size=None, + scale_factor=None, + mode="nearest", + align_corners=None, + recompute_scale_factor=None, + antialias=False, +): if input.device.type == "mps" and input.dtype == torch.float16: - return _torch_interpolate(input.float(), size, scale_factor, mode, align_corners, recompute_scale_factor, antialias).half() + return _torch_interpolate( + input.float(), size, scale_factor, mode, align_corners, recompute_scale_factor, antialias + ).half() else: return _torch_interpolate(input, size, scale_factor, mode, align_corners, recompute_scale_factor, antialias) + torch.nn.functional.interpolate = new_torch_interpolate # TODO: refactor it _SlicedAttnProcessor = diffusers.models.attention_processor.SlicedAttnProcessor + + class ChunkedSlicedAttnProcessor: r""" Processor for implementing sliced attention. @@ -78,7 +102,7 @@ class ChunkedSlicedAttnProcessor: def __init__(self, slice_size): assert isinstance(slice_size, int) - slice_size = 1 # TODO: maybe implement chunking in batches too when enough memory + slice_size = 1 # TODO: maybe implement chunking in batches too when enough memory self.slice_size = slice_size self._sliced_attn_processor = _SlicedAttnProcessor(slice_size) @@ -121,7 +145,9 @@ class ChunkedSlicedAttnProcessor: (batch_size_attention, query_tokens, dim // attn.heads), device=query.device, dtype=query.dtype ) - chunk_tmp_tensor = torch.empty(self.slice_size, query.shape[1], key.shape[1], dtype=query.dtype, device=query.device) + chunk_tmp_tensor = torch.empty( + self.slice_size, query.shape[1], key.shape[1], dtype=query.dtype, device=query.device + ) for i in range(batch_size_attention // self.slice_size): start_idx = i * self.slice_size @@ -131,7 +157,15 @@ class ChunkedSlicedAttnProcessor: key_slice = key[start_idx:end_idx] attn_mask_slice = attention_mask[start_idx:end_idx] if attention_mask is not None else None - self.get_attention_scores_chunked(attn, query_slice, key_slice, attn_mask_slice, hidden_states[start_idx:end_idx], value[start_idx:end_idx], chunk_tmp_tensor) + self.get_attention_scores_chunked( + attn, + query_slice, + key_slice, + attn_mask_slice, + hidden_states[start_idx:end_idx], + value[start_idx:end_idx], + chunk_tmp_tensor, + ) hidden_states = attn.batch_to_head_dim(hidden_states) @@ -150,7 +184,6 @@ class ChunkedSlicedAttnProcessor: return hidden_states - def get_attention_scores_chunked(self, attn, query, key, attention_mask, hidden_states, value, chunk): # batch size = 1 assert query.shape[0] == 1 @@ -163,14 +196,14 @@ class ChunkedSlicedAttnProcessor: query = query.float() key = key.float() - #out_item_size = query.dtype.itemsize - #if attn.upcast_attention: + # out_item_size = query.dtype.itemsize + # if attn.upcast_attention: # out_item_size = torch.float32.itemsize out_item_size = query.element_size() if attn.upcast_attention: out_item_size = 4 - chunk_size = 2 ** 29 + chunk_size = 2**29 out_size = query.shape[1] * key.shape[1] * out_item_size chunks_count = min(query.shape[1], math.ceil((out_size - 1) / chunk_size)) @@ -181,8 +214,8 @@ class ChunkedSlicedAttnProcessor: def _get_chunk_view(tensor, start, length): if start + length > tensor.shape[1]: length = tensor.shape[1] - start - #print(f"view: [{tensor.shape[0]},{tensor.shape[1]},{tensor.shape[2]}] - start: {start}, length: {length}") - return tensor[:,start:start+length] + # print(f"view: [{tensor.shape[0]},{tensor.shape[1]},{tensor.shape[2]}] - start: {start}, length: {length}") + return tensor[:, start : start + length] for chunk_pos in range(0, query.shape[1], chunk_step): if attention_mask is not None: @@ -196,7 +229,7 @@ class ChunkedSlicedAttnProcessor: ) else: torch.baddbmm( - torch.zeros((1,1,1), device=query.device, dtype=query.dtype), + torch.zeros((1, 1, 1), device=query.device, dtype=query.dtype), _get_chunk_view(query, chunk_pos, chunk_step), key, beta=0, @@ -206,7 +239,7 @@ class ChunkedSlicedAttnProcessor: chunk = chunk.softmax(dim=-1) torch.bmm(chunk, value, out=_get_chunk_view(hidden_states, chunk_pos, chunk_step)) - #del chunk + # del chunk diffusers.models.attention_processor.SlicedAttnProcessor = ChunkedSlicedAttnProcessor diff --git a/invokeai/backend/util/util.py b/invokeai/backend/util/util.py index 1cc632e483..f3c182c063 100644 --- a/invokeai/backend/util/util.py +++ b/invokeai/backend/util/util.py @@ -32,9 +32,7 @@ def log_txt_as_img(wh, xc, size=10): draw = ImageDraw.Draw(txt) font = ImageFont.load_default() nc = int(40 * (wh[0] / 256)) - lines = "\n".join( - xc[bi][start : start + nc] for start in range(0, len(xc[bi]), nc) - ) + lines = "\n".join(xc[bi][start : start + nc] for start in range(0, len(xc[bi]), nc)) try: draw.text((0, 0), lines, fill="black", font=font) @@ -81,9 +79,7 @@ def mean_flat(tensor): def count_params(model, verbose=False): total_params = sum(p.numel() for p in model.parameters()) if verbose: - logger.debug( - f"{model.__class__.__name__} has {total_params * 1.e-6:.2f} M params." - ) + logger.debug(f"{model.__class__.__name__} has {total_params * 1.e-6:.2f} M params.") return total_params @@ -154,21 +150,12 @@ def parallel_data_prefetch( proc = Thread # spawn processes if target_data_type == "ndarray": - arguments = [ - [func, Q, part, i, use_worker_id] - for i, part in enumerate(np.array_split(data, n_proc)) - ] + arguments = [[func, Q, part, i, use_worker_id] for i, part in enumerate(np.array_split(data, n_proc))] else: - step = ( - int(len(data) / n_proc + 1) - if len(data) % n_proc != 0 - else int(len(data) / n_proc) - ) + step = int(len(data) / n_proc + 1) if len(data) % n_proc != 0 else int(len(data) / n_proc) arguments = [ [func, Q, part, i, use_worker_id] - for i, part in enumerate( - [data[i : i + step] for i in range(0, len(data), step)] - ) + for i, part in enumerate([data[i : i + step] for i in range(0, len(data), step)]) ] processes = [] for i in range(n_proc): @@ -220,9 +207,7 @@ def parallel_data_prefetch( return gather_res -def rand_perlin_2d( - shape, res, device, fade=lambda t: 6 * t**5 - 15 * t**4 + 10 * t**3 -): +def rand_perlin_2d(shape, res, device, fade=lambda t: 6 * t**5 - 15 * t**4 + 10 * t**3): delta = (res[0] / shape[0], res[1] / shape[1]) d = (shape[0] // res[0], shape[1] // res[1]) @@ -265,9 +250,9 @@ def rand_perlin_2d( n01 = dot(tile_grads([0, -1], [1, None]), [0, -1]).to(device) n11 = dot(tile_grads([1, None], [1, None]), [-1, -1]).to(device) t = fade(grid[: shape[0], : shape[1]]) - noise = math.sqrt(2) * torch.lerp( - torch.lerp(n00, n10, t[..., 0]), torch.lerp(n01, n11, t[..., 0]), t[..., 1] - ).to(device) + noise = math.sqrt(2) * torch.lerp(torch.lerp(n00, n10, t[..., 0]), torch.lerp(n01, n11, t[..., 0]), t[..., 1]).to( + device + ) return noise.to(dtype=torch_dtype(device)) @@ -276,9 +261,7 @@ def ask_user(question: str, answers: list): user_prompt = f"\n>> {question} {answers}: " invalid_answer_msg = "Invalid answer. Please try again." - pose_question = chain( - [user_prompt], repeat("\n".join([invalid_answer_msg, user_prompt])) - ) + pose_question = chain([user_prompt], repeat("\n".join([invalid_answer_msg, user_prompt]))) user_answers = map(input, pose_question) valid_response = next(filter(answers.__contains__, user_answers)) return valid_response @@ -303,9 +286,7 @@ def download_with_resume(url: str, dest: Path, access_token: str = None) -> Path if dest.is_dir(): try: - file_name = re.search( - 'filename="(.+)"', resp.headers.get("Content-Disposition") - ).group(1) + file_name = re.search('filename="(.+)"', resp.headers.get("Content-Disposition")).group(1) except: file_name = os.path.basename(url) dest = dest / file_name @@ -322,7 +303,7 @@ def download_with_resume(url: str, dest: Path, access_token: str = None) -> Path logger.warning("corrupt existing file found. re-downloading") os.remove(dest) exist_size = 0 - + if resp.status_code == 416 or (content_length > 0 and exist_size == content_length): logger.warning(f"{dest}: complete file found. Skipping.") return dest @@ -377,16 +358,16 @@ def image_to_dataURL(image: Image.Image, image_format: str = "PNG") -> str: buffered = io.BytesIO() image.save(buffered, format=image_format) mime_type = Image.MIME.get(image_format.upper(), "image/" + image_format.lower()) - image_base64 = f"data:{mime_type};base64," + base64.b64encode( - buffered.getvalue() - ).decode("UTF-8") + image_base64 = f"data:{mime_type};base64," + base64.b64encode(buffered.getvalue()).decode("UTF-8") return image_base64 + class Chdir(object): - '''Context manager to chdir to desired directory and change back after context exits: + """Context manager to chdir to desired directory and change back after context exits: Args: path (Path): The path to the cwd - ''' + """ + def __init__(self, path: Path): self.path = path self.original = Path().absolute() @@ -394,5 +375,5 @@ class Chdir(object): def __enter__(self): os.chdir(self.path) - def __exit__(self,*args): + def __exit__(self, *args): os.chdir(self.original) diff --git a/invokeai/backend/web/invoke_ai_web_server.py b/invokeai/backend/web/invoke_ai_web_server.py index eec02cd9dc..88eb77551f 100644 --- a/invokeai/backend/web/invoke_ai_web_server.py +++ b/invokeai/backend/web/invoke_ai_web_server.py @@ -64,10 +64,7 @@ class InvokeAIWebServer: self.ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg"} def allowed_file(self, filename: str) -> bool: - return ( - "." in filename - and filename.rsplit(".", 1)[1].lower() in self.ALLOWED_EXTENSIONS - ) + return "." in filename and filename.rsplit(".", 1)[1].lower() in self.ALLOWED_EXTENSIONS def run(self): self.setup_app() @@ -99,9 +96,7 @@ class InvokeAIWebServer: _cors = _cors.split(",") socketio_args["cors_allowed_origins"] = _cors - self.app = Flask( - __name__, static_url_path="", static_folder=frontend.__path__[0] - ) + self.app = Flask(__name__, static_url_path="", static_folder=frontend.__path__[0]) self.socketio = SocketIO(self.app, **socketio_args) @@ -192,9 +187,7 @@ class InvokeAIWebServer: (width, height) = pil_image.size - thumbnail_path = save_thumbnail( - pil_image, os.path.basename(file_path), self.thumbnail_image_path - ) + thumbnail_path = save_thumbnail(pil_image, os.path.basename(file_path), self.thumbnail_image_path) response = { "url": self.get_url_from_image_path(file_path), @@ -237,12 +230,8 @@ class InvokeAIWebServer: f"Point your browser at http{'s' if useSSL else ''}://localhost:{self.port} or use the host's DNS name or IP address." ) else: - logger.info( - "Default host address now 127.0.0.1 (localhost). Use --host 0.0.0.0 to bind any address." - ) - logger.info( - f"Point your browser at http{'s' if useSSL else ''}://{self.host}:{self.port}" - ) + logger.info("Default host address now 127.0.0.1 (localhost). Use --host 0.0.0.0 to bind any address.") + logger.info(f"Point your browser at http{'s' if useSSL else ''}://{self.host}:{self.port}") if not useSSL: self.socketio.run(app=self.app, host=self.host, port=self.port) else: @@ -392,22 +381,16 @@ class InvokeAIWebServer: @socketio.on("convertToDiffusers") def convert_to_diffusers(model_to_convert: dict): try: - if model_info := self.generate.model_manager.model_info( - model_name=model_to_convert["model_name"] - ): + if model_info := self.generate.model_manager.model_info(model_name=model_to_convert["model_name"]): if "weights" in model_info: ckpt_path = Path(model_info["weights"]) original_config_file = Path(model_info["config"]) model_name = model_to_convert["model_name"] model_description = model_info["description"] else: - self.socketio.emit( - "error", {"message": "Model is not a valid checkpoint file"} - ) + self.socketio.emit("error", {"message": "Model is not a valid checkpoint file"}) else: - self.socketio.emit( - "error", {"message": "Could not retrieve model info."} - ) + self.socketio.emit("error", {"message": "Could not retrieve model info."}) if not ckpt_path.is_absolute(): ckpt_path = Path(Globals.root, ckpt_path) @@ -415,22 +398,13 @@ class InvokeAIWebServer: if original_config_file and not original_config_file.is_absolute(): original_config_file = Path(Globals.root, original_config_file) - diffusers_path = Path( - ckpt_path.parent.absolute(), f"{model_name}_diffusers" - ) + diffusers_path = Path(ckpt_path.parent.absolute(), f"{model_name}_diffusers") if model_to_convert["save_location"] == "root": - diffusers_path = Path( - global_converted_ckpts_dir(), f"{model_name}_diffusers" - ) + diffusers_path = Path(global_converted_ckpts_dir(), f"{model_name}_diffusers") - if ( - model_to_convert["save_location"] == "custom" - and model_to_convert["custom_location"] is not None - ): - diffusers_path = Path( - model_to_convert["custom_location"], f"{model_name}_diffusers" - ) + if model_to_convert["save_location"] == "custom" and model_to_convert["custom_location"] is not None: + diffusers_path = Path(model_to_convert["custom_location"], f"{model_name}_diffusers") if diffusers_path.exists(): shutil.rmtree(diffusers_path) @@ -462,10 +436,7 @@ class InvokeAIWebServer: def merge_diffusers_models(model_merge_info: dict): try: models_to_merge = model_merge_info["models_to_merge"] - model_ids_or_paths = [ - self.generate.model_manager.model_name_or_path(x) - for x in models_to_merge - ] + model_ids_or_paths = [self.generate.model_manager.model_name_or_path(x) for x in models_to_merge] merged_pipe = merge_diffusion_models( model_ids_or_paths, model_merge_info["alpha"], @@ -487,15 +458,11 @@ class InvokeAIWebServer: commit_to_conf=opt.conf, ) - if vae := self.generate.model_manager.config[models_to_merge[0]].get( - "vae", None - ): + if vae := self.generate.model_manager.config[models_to_merge[0]].get("vae", None): logger.info(f"Using configured VAE assigned to {models_to_merge[0]}") merged_model_config.update(vae=vae) - self.generate.model_manager.import_diffuser_model( - dump_path, **merged_model_config - ) + self.generate.model_manager.import_diffuser_model(dump_path, **merged_model_config) new_model_list = self.generate.model_manager.list_models() socketio.emit( @@ -525,9 +492,7 @@ class InvokeAIWebServer: ) os.remove(thumbnail_path) except Exception as e: - socketio.emit( - "error", {"message": f"Unable to delete {f}: {str(e)}"} - ) + socketio.emit("error", {"message": f"Unable to delete {f}: {str(e)}"}) pass socketio.emit("tempFolderEmptied") @@ -550,9 +515,7 @@ class InvokeAIWebServer: (width, height) = pil_image.size - thumbnail_path = save_thumbnail( - pil_image, os.path.basename(new_path), self.thumbnail_image_path - ) + thumbnail_path = save_thumbnail(pil_image, os.path.basename(new_path), self.thumbnail_image_path) image_array = [ { @@ -577,18 +540,14 @@ class InvokeAIWebServer: @socketio.on("requestLatestImages") def handle_request_latest_images(category, latest_mtime): try: - base_path = ( - self.result_path if category == "result" else self.init_image_path - ) + base_path = self.result_path if category == "result" else self.init_image_path paths = [] for ext in ("*.png", "*.jpg", "*.jpeg"): paths.extend(glob.glob(os.path.join(base_path, ext))) - image_paths = sorted( - paths, key=lambda x: os.path.getmtime(x), reverse=True - ) + image_paths = sorted(paths, key=lambda x: os.path.getmtime(x), reverse=True) image_paths = list( filter( @@ -609,16 +568,12 @@ class InvokeAIWebServer: pil_image = Image.open(path) (width, height) = pil_image.size - thumbnail_path = save_thumbnail( - pil_image, os.path.basename(path), self.thumbnail_image_path - ) + thumbnail_path = save_thumbnail(pil_image, os.path.basename(path), self.thumbnail_image_path) image_array.append( { "url": self.get_url_from_image_path(path), - "thumbnail": self.get_url_from_image_path( - thumbnail_path - ), + "thumbnail": self.get_url_from_image_path(thumbnail_path), "mtime": os.path.getmtime(path), "metadata": metadata.get("sd-metadata"), "dreamPrompt": metadata.get("Dream"), @@ -628,9 +583,7 @@ class InvokeAIWebServer: } ) except Exception as e: - socketio.emit( - "error", {"message": f"Unable to load {path}: {str(e)}"} - ) + socketio.emit("error", {"message": f"Unable to load {path}: {str(e)}"}) pass socketio.emit( @@ -645,17 +598,13 @@ class InvokeAIWebServer: try: page_size = 50 - base_path = ( - self.result_path if category == "result" else self.init_image_path - ) + base_path = self.result_path if category == "result" else self.init_image_path paths = [] for ext in ("*.png", "*.jpg", "*.jpeg"): paths.extend(glob.glob(os.path.join(base_path, ext))) - image_paths = sorted( - paths, key=lambda x: os.path.getmtime(x), reverse=True - ) + image_paths = sorted(paths, key=lambda x: os.path.getmtime(x), reverse=True) if earliest_mtime: image_paths = list( @@ -679,16 +628,12 @@ class InvokeAIWebServer: pil_image = Image.open(path) (width, height) = pil_image.size - thumbnail_path = save_thumbnail( - pil_image, os.path.basename(path), self.thumbnail_image_path - ) + thumbnail_path = save_thumbnail(pil_image, os.path.basename(path), self.thumbnail_image_path) image_array.append( { "url": self.get_url_from_image_path(path), - "thumbnail": self.get_url_from_image_path( - thumbnail_path - ), + "thumbnail": self.get_url_from_image_path(thumbnail_path), "mtime": os.path.getmtime(path), "metadata": metadata.get("sd-metadata"), "dreamPrompt": metadata.get("Dream"), @@ -699,9 +644,7 @@ class InvokeAIWebServer: ) except Exception as e: logger.info(f"Unable to load {path}") - socketio.emit( - "error", {"message": f"Unable to load {path}: {str(e)}"} - ) + socketio.emit("error", {"message": f"Unable to load {path}: {str(e)}"}) pass socketio.emit( @@ -716,9 +659,7 @@ class InvokeAIWebServer: self.handle_exceptions(e) @socketio.on("generateImage") - def handle_generate_image_event( - generation_parameters, esrgan_parameters, facetool_parameters - ): + def handle_generate_image_event(generation_parameters, esrgan_parameters, facetool_parameters): try: # truncate long init_mask/init_img base64 if needed printable_parameters = { @@ -726,14 +667,10 @@ class InvokeAIWebServer: } if "init_img" in generation_parameters: - printable_parameters["init_img"] = ( - printable_parameters["init_img"][:64] + "..." - ) + printable_parameters["init_img"] = printable_parameters["init_img"][:64] + "..." if "init_mask" in generation_parameters: - printable_parameters["init_mask"] = ( - printable_parameters["init_mask"][:64] + "..." - ) + printable_parameters["init_mask"] = printable_parameters["init_mask"][:64] + "..." logger.info(f"Image Generation Parameters:\n\n{printable_parameters}\n") logger.info(f"ESRGAN Parameters: {esrgan_parameters}") @@ -750,18 +687,14 @@ class InvokeAIWebServer: @socketio.on("runPostprocessing") def handle_run_postprocessing(original_image, postprocessing_parameters): try: - logger.info( - f'Postprocessing requested for "{original_image["url"]}": {postprocessing_parameters}' - ) + logger.info(f'Postprocessing requested for "{original_image["url"]}": {postprocessing_parameters}') progress = Progress() socketio.emit("progressUpdate", progress.to_formatted_dict()) eventlet.sleep(0) - original_image_path = self.get_image_path_from_url( - original_image["url"] - ) + original_image_path = self.get_image_path_from_url(original_image["url"]) image = Image.open(original_image_path) @@ -801,14 +734,10 @@ class InvokeAIWebServer: strength=postprocessing_parameters["facetool_strength"], fidelity=postprocessing_parameters["codeformer_fidelity"], seed=seed, - device="cpu" - if str(self.generate.device) == "mps" - else self.generate.device, + device="cpu" if str(self.generate.device) == "mps" else self.generate.device, ) else: - raise TypeError( - f'{postprocessing_parameters["type"]} is not a valid postprocessing type' - ) + raise TypeError(f'{postprocessing_parameters["type"]} is not a valid postprocessing type') progress.set_current_status("common.statusSavingImage") socketio.emit("progressUpdate", progress.to_formatted_dict()) @@ -832,9 +761,7 @@ class InvokeAIWebServer: postprocessing=postprocessing_parameters["type"], ) - thumbnail_path = save_thumbnail( - image, os.path.basename(path), self.thumbnail_image_path - ) + thumbnail_path = save_thumbnail(image, os.path.basename(path), self.thumbnail_image_path) self.write_log_message( f'[Postprocessed] "{original_image_path}" > "{path}": {postprocessing_parameters}' @@ -901,17 +828,13 @@ class InvokeAIWebServer: "app_version": APP_VERSION, } - def generate_images( - self, generation_parameters, esrgan_parameters, facetool_parameters - ): + def generate_images(self, generation_parameters, esrgan_parameters, facetool_parameters): try: self.canceled.clear() step_index = 1 prior_variations = ( - generation_parameters["with_variations"] - if "with_variations" in generation_parameters - else [] + generation_parameters["with_variations"] if "with_variations" in generation_parameters else [] ) actual_generation_mode = generation_parameters["generation_mode"] @@ -943,9 +866,7 @@ class InvokeAIWebServer: original_bounding_box = generation_parameters["bounding_box"].copy() - initial_image = dataURL_to_image( - generation_parameters["init_img"] - ).convert("RGBA") + initial_image = dataURL_to_image(generation_parameters["init_img"]).convert("RGBA") """ The outpaint image and mask are pre-cropped by the UI, so the bounding box we pass @@ -962,13 +883,9 @@ class InvokeAIWebServer: generation_parameters["bounding_box"]["y"] = 0 # Convert mask dataURL to an image and convert to greyscale - mask_image = dataURL_to_image( - generation_parameters["init_mask"] - ).convert("L") + mask_image = dataURL_to_image(generation_parameters["init_mask"]).convert("L") - actual_generation_mode = get_canvas_generation_mode( - initial_image, mask_image - ) + actual_generation_mode = get_canvas_generation_mode(initial_image, mask_image) """ Apply the mask to the init image, creating a "mask" image with @@ -1018,9 +935,7 @@ class InvokeAIWebServer: elif generation_parameters["generation_mode"] == "img2img": init_img_url = generation_parameters["init_img"] init_img_path = self.get_image_path_from_url(init_img_url) - generation_parameters["init_img"] = Image.open(init_img_path).convert( - "RGB" - ) + generation_parameters["init_img"] = Image.open(init_img_path).convert("RGB") def image_progress(intermediate_state: PipelineIntermediateState): if self.canceled.is_set(): @@ -1046,9 +961,7 @@ class InvokeAIWebServer: } progress.set_current_step(step + 1) - progress.set_current_status( - f"{generation_messages[actual_generation_mode]}" - ) + progress.set_current_status(f"{generation_messages[actual_generation_mode]}") progress.set_current_status_has_steps(True) if ( @@ -1057,9 +970,7 @@ class InvokeAIWebServer: and step < generation_parameters["steps"] - 1 ): image = self.generate.sample_to_image(sample) - metadata = self.parameters_to_generated_image_metadata( - generation_parameters - ) + metadata = self.parameters_to_generated_image_metadata(generation_parameters) command = parameters_to_command(generation_parameters) (width, height) = image.size @@ -1140,15 +1051,10 @@ class InvokeAIWebServer: all_parameters = generation_parameters postprocessing = False - if ( - "variation_amount" in all_parameters - and all_parameters["variation_amount"] > 0 - ): + if "variation_amount" in all_parameters and all_parameters["variation_amount"] > 0: first_seed = first_seed or seed this_variation = [[seed, all_parameters["variation_amount"]]] - all_parameters["with_variations"] = ( - prior_variations + this_variation - ) + all_parameters["with_variations"] = prior_variations + this_variation all_parameters["seed"] = first_seed elif "with_variations" in all_parameters: all_parameters["seed"] = first_seed @@ -1186,9 +1092,7 @@ class InvokeAIWebServer: if facetool_parameters["type"] == "gfpgan": progress.set_current_status("common.statusRestoringFacesGFPGAN") elif facetool_parameters["type"] == "codeformer": - progress.set_current_status( - "common.statusRestoringFacesCodeFormer" - ) + progress.set_current_status("common.statusRestoringFacesCodeFormer") progress.set_current_status_has_steps(False) self.socketio.emit("progressUpdate", progress.to_formatted_dict()) @@ -1206,18 +1110,12 @@ class InvokeAIWebServer: strength=facetool_parameters["strength"], fidelity=facetool_parameters["codeformer_fidelity"], seed=seed, - device="cpu" - if str(self.generate.device) == "mps" - else self.generate.device, + device="cpu" if str(self.generate.device) == "mps" else self.generate.device, ) - all_parameters["codeformer_fidelity"] = facetool_parameters[ - "codeformer_fidelity" - ] + all_parameters["codeformer_fidelity"] = facetool_parameters["codeformer_fidelity"] postprocessing = True - all_parameters["facetool_strength"] = facetool_parameters[ - "strength" - ] + all_parameters["facetool_strength"] = facetool_parameters["strength"] all_parameters["facetool_type"] = facetool_parameters["type"] progress.set_current_status("common.statusSavingImage") @@ -1226,9 +1124,7 @@ class InvokeAIWebServer: # restore the stashed URLS and discard the paths, we are about to send the result to client all_parameters["init_img"] = ( - init_img_url - if generation_parameters["generation_mode"] == "img2img" - else "" + init_img_url if generation_parameters["generation_mode"] == "img2img" else "" ) if "init_mask" in all_parameters: @@ -1246,8 +1142,7 @@ class InvokeAIWebServer: generated_image_outdir = ( self.result_path - if generation_parameters["generation_mode"] - in ["txt2img", "img2img"] + if generation_parameters["generation_mode"] in ["txt2img", "img2img"] else self.temp_image_path ) @@ -1259,9 +1154,7 @@ class InvokeAIWebServer: postprocessing=postprocessing, ) - thumbnail_path = save_thumbnail( - image, os.path.basename(path), self.thumbnail_image_path - ) + thumbnail_path = save_thumbnail(image, os.path.basename(path), self.thumbnail_image_path) logger.info(f'Image generated: "{path}"\n') self.write_log_message(f'[Generated] "{path}": {command}') @@ -1281,14 +1174,10 @@ class InvokeAIWebServer: tokens = ( None if type(parsed_prompt) is Blend - else get_tokens_for_prompt_object( - model.tokenizer, parsed_prompt - ) + else get_tokens_for_prompt_object(model.tokenizer, parsed_prompt) ) attention_maps_image_base64_url = ( - None - if attention_maps_image is None - else image_to_dataURL(attention_maps_image) + None if attention_maps_image is None else image_to_dataURL(attention_maps_image) ) self.socketio.emit( @@ -1382,9 +1271,7 @@ class InvokeAIWebServer: } if parameters["facetool_type"] == "codeformer": - facetool_parameters["fidelity"] = float( - parameters["codeformer_fidelity"] - ) + facetool_parameters["fidelity"] = float(parameters["codeformer_fidelity"]) postprocessing.append(facetool_parameters) @@ -1398,9 +1285,7 @@ class InvokeAIWebServer: } ) - rfc_dict["postprocessing"] = ( - postprocessing if len(postprocessing) > 0 else None - ) + rfc_dict["postprocessing"] = postprocessing if len(postprocessing) > 0 else None # semantic drift rfc_dict["sampler"] = parameters["sampler_name"] @@ -1409,22 +1294,15 @@ class InvokeAIWebServer: variations = [] if "with_variations" in parameters: - variations = [ - {"seed": x[0], "weight": x[1]} - for x in parameters["with_variations"] - ] + variations = [{"seed": x[0], "weight": x[1]} for x in parameters["with_variations"]] rfc_dict["variations"] = variations if rfc_dict["type"] == "img2img": rfc_dict["strength"] = parameters["strength"] rfc_dict["fit"] = parameters["fit"] # TODO: Noncompliant - rfc_dict["orig_hash"] = calculate_init_img_hash( - self.get_image_path_from_url(parameters["init_img"]) - ) - rfc_dict["init_image_path"] = parameters[ - "init_img" - ] # TODO: Noncompliant + rfc_dict["orig_hash"] = calculate_init_img_hash(self.get_image_path_from_url(parameters["init_img"])) + rfc_dict["init_image_path"] = parameters["init_img"] # TODO: Noncompliant metadata["image"] = rfc_dict @@ -1433,9 +1311,7 @@ class InvokeAIWebServer: except Exception as e: self.handle_exceptions(e) - def parameters_to_post_processed_image_metadata( - self, parameters, original_image_path - ): + def parameters_to_post_processed_image_metadata(self, parameters, original_image_path): try: current_metadata = retrieve_metadata(original_image_path)["sd-metadata"] postprocessing_metadata = {} @@ -1447,9 +1323,7 @@ class InvokeAIWebServer: if "image" not in current_metadata: current_metadata["image"] = {} - orig_hash = calculate_init_img_hash( - self.get_image_path_from_url(original_image_path) - ) + orig_hash = calculate_init_img_hash(self.get_image_path_from_url(original_image_path)) postprocessing_metadata["orig_path"] = (original_image_path,) postprocessing_metadata["orig_hash"] = orig_hash @@ -1473,9 +1347,7 @@ class InvokeAIWebServer: if "postprocessing" in current_metadata["image"] and isinstance( current_metadata["image"]["postprocessing"], list ): - current_metadata["image"]["postprocessing"].append( - postprocessing_metadata - ) + current_metadata["image"]["postprocessing"].append(postprocessing_metadata) else: current_metadata["image"]["postprocessing"] = [postprocessing_metadata] @@ -1556,29 +1428,17 @@ class InvokeAIWebServer: """Given a url to an image used by the client, returns the absolute file path to that image""" try: if "init-images" in url: - return os.path.abspath( - os.path.join(self.init_image_path, os.path.basename(url)) - ) + return os.path.abspath(os.path.join(self.init_image_path, os.path.basename(url))) elif "mask-images" in url: - return os.path.abspath( - os.path.join(self.mask_image_path, os.path.basename(url)) - ) + return os.path.abspath(os.path.join(self.mask_image_path, os.path.basename(url))) elif "intermediates" in url: - return os.path.abspath( - os.path.join(self.intermediate_path, os.path.basename(url)) - ) + return os.path.abspath(os.path.join(self.intermediate_path, os.path.basename(url))) elif "temp-images" in url: - return os.path.abspath( - os.path.join(self.temp_image_path, os.path.basename(url)) - ) + return os.path.abspath(os.path.join(self.temp_image_path, os.path.basename(url))) elif "thumbnails" in url: - return os.path.abspath( - os.path.join(self.thumbnail_image_path, os.path.basename(url)) - ) + return os.path.abspath(os.path.join(self.thumbnail_image_path, os.path.basename(url))) else: - return os.path.abspath( - os.path.join(self.result_path, os.path.basename(url)) - ) + return os.path.abspath(os.path.join(self.result_path, os.path.basename(url))) except Exception as e: self.handle_exceptions(e) @@ -1632,18 +1492,14 @@ class Progress: self.total_steps = ( self._calculate_real_steps( steps=generation_parameters["steps"], - strength=generation_parameters["strength"] - if "strength" in generation_parameters - else None, + strength=generation_parameters["strength"] if "strength" in generation_parameters else None, has_init_image="init_img" in generation_parameters, ) if generation_parameters else 1 ) self.current_iteration = 1 - self.total_iterations = ( - generation_parameters["iterations"] if generation_parameters else 1 - ) + self.total_iterations = generation_parameters["iterations"] if generation_parameters else 1 self.current_status = "common.statusPreparing" self.is_processing = True self.current_status_has_steps = False @@ -1703,9 +1559,7 @@ class CanceledException(Exception): pass -def copy_image_from_bounding_box( - image: ImageType, x: int, y: int, width: int, height: int -) -> ImageType: +def copy_image_from_bounding_box(image: ImageType, x: int, y: int, width: int, height: int) -> ImageType: """ Returns a copy an image, cropped to a bounding box. """ @@ -1740,9 +1594,7 @@ def image_to_dataURL(image: ImageType, image_format: str = "PNG") -> str: buffered = io.BytesIO() image.save(buffered, format=image_format) mime_type = Image.MIME.get(image_format.upper(), "image/" + image_format.lower()) - image_base64 = f"data:{mime_type};base64," + base64.b64encode( - buffered.getvalue() - ).decode("UTF-8") + image_base64 = f"data:{mime_type};base64," + base64.b64encode(buffered.getvalue()).decode("UTF-8") return image_base64 diff --git a/invokeai/backend/web/modules/get_canvas_generation_mode.py b/invokeai/backend/web/modules/get_canvas_generation_mode.py index 55955cc33c..6d680016e7 100644 --- a/invokeai/backend/web/modules/get_canvas_generation_mode.py +++ b/invokeai/backend/web/modules/get_canvas_generation_mode.py @@ -40,9 +40,7 @@ def get_canvas_generation_mode( init_img_has_transparency = check_for_any_transparency(init_img) if init_img_has_transparency: - init_img_is_fully_transparent = ( - True if init_img_alpha_mask.getbbox() is None else False - ) + init_img_is_fully_transparent = True if init_img_alpha_mask.getbbox() is None else False """ Mask images are white in areas where no change should be made, black where changes diff --git a/invokeai/backend/web/modules/parameters.py b/invokeai/backend/web/modules/parameters.py index 440f21a947..8ab74adb92 100644 --- a/invokeai/backend/web/modules/parameters.py +++ b/invokeai/backend/web/modules/parameters.py @@ -10,7 +10,7 @@ SAMPLER_CHOICES = [ "lms_k", "pndm", "heun", - 'heun_k', + "heun_k", "euler", "euler_k", "euler_a", @@ -76,9 +76,7 @@ def parameters_to_command(params): if "variation_amount" in params and params["variation_amount"] > 0: switches.append(f'-v {params["variation_amount"]}') if "with_variations" in params: - seed_weight_pairs = ",".join( - f"{seed}:{weight}" for seed, weight in params["with_variations"] - ) + seed_weight_pairs = ",".join(f"{seed}:{weight}" for seed, weight in params["with_variations"]) switches.append(f"-V {seed_weight_pairs}") return " ".join(switches) diff --git a/invokeai/configs/INITIAL_MODELS.yaml b/invokeai/configs/INITIAL_MODELS.yaml index e148ee9b55..86357e7b56 100644 --- a/invokeai/configs/INITIAL_MODELS.yaml +++ b/invokeai/configs/INITIAL_MODELS.yaml @@ -16,14 +16,18 @@ sd-2/main/stable-diffusion-2-inpainting: description: Stable Diffusion version 2.0 inpainting model (5.21 GB) repo_id: stabilityai/stable-diffusion-2-inpainting recommended: False -sdxl/main/stable-diffusion-xl-base-0-9: - description: Stable Diffusion XL base model (12 GB; access token required) - repo_id: stabilityai/stable-diffusion-xl-base-0.9 - recommended: False -sdxl-refiner/main/stable-diffusion-xl-refiner-0-9: - description: Stable Diffusion XL refiner model (12 GB; access token required) - repo_id: stabilityai/stable-diffusion-xl-refiner-0.9 +sdxl/main/stable-diffusion-xl-base-1-0: + description: Stable Diffusion XL base model (12 GB) + repo_id: stabilityai/stable-diffusion-xl-base-1.0 recommended: False +sdxl-refiner/main/stable-diffusion-xl-refiner-1-0: + description: Stable Diffusion XL refiner model (12 GB) + repo_id: stabilityai/stable-diffusion-xl-refiner-1.0 + recommended: false +sdxl/vae/sdxl-1-0-vae-fix: + description: Fine tuned version of the SDXL-1.0 VAE + repo_id: madebyollin/sdxl-vae-fp16-fix + recommended: true sd-1/main/Analog-Diffusion: description: An SD-1.5 model trained on diverse analog photographs (2.13 GB) repo_id: wavymulder/Analog-Diffusion @@ -48,10 +52,6 @@ sd-1/main/openjourney: description: An SD 1.5 model fine tuned on Midjourney; prompt with "mdjrny-v4 style" (2.13 GB) repo_id: prompthero/openjourney recommended: False -sd-1/main/portraitplus: - description: An SD-1.5 model trained on close range portraits of people; prompt with "portrait+" (2.13 GB) - repo_id: wavymulder/portraitplus - recommended: False sd-1/main/seek.art_MEGA: repo_id: coreco/seek.art_MEGA description: A general use SD-1.5 "anything" model that supports multiple styles (2.1 GB) @@ -60,10 +60,6 @@ sd-1/main/trinart_stable_diffusion_v2: description: An SD-1.5 model finetuned with ~40K assorted high resolution manga/anime-style images (2.13 GB) repo_id: naclbit/trinart_stable_diffusion_v2 recommended: False -sd-1/main/waifu-diffusion: - description: An SD-1.5 model trained on 680k anime/manga-style images (2.13 GB) - repo_id: hakurei/waifu-diffusion - recommended: False sd-1/controlnet/canny: repo_id: lllyasviel/control_v11p_sd15_canny recommended: True diff --git a/invokeai/frontend/__init__.py b/invokeai/frontend/__init__.py index 98fdf870e9..19eafe46c4 100644 --- a/invokeai/frontend/__init__.py +++ b/invokeai/frontend/__init__.py @@ -1,3 +1,3 @@ -''' +""" Initialization file for invokeai.frontend -''' +""" diff --git a/invokeai/frontend/install/invokeai_update.py b/invokeai/frontend/install/invokeai_update.py index f73f670496..56d1a313c7 100644 --- a/invokeai/frontend/install/invokeai_update.py +++ b/invokeai/frontend/install/invokeai_update.py @@ -1,7 +1,7 @@ -''' +""" Minimalist updater script. Prompts user for the tag or branch to update to and runs pip install . -''' +""" import os import platform import pkg_resources @@ -15,10 +15,10 @@ from rich.style import Style from invokeai.version import __version__ -INVOKE_AI_SRC="https://github.com/invoke-ai/InvokeAI/archive" -INVOKE_AI_TAG="https://github.com/invoke-ai/InvokeAI/archive/refs/tags" -INVOKE_AI_BRANCH="https://github.com/invoke-ai/InvokeAI/archive/refs/heads" -INVOKE_AI_REL="https://api.github.com/repos/invoke-ai/InvokeAI/releases" +INVOKE_AI_SRC = "https://github.com/invoke-ai/InvokeAI/archive" +INVOKE_AI_TAG = "https://github.com/invoke-ai/InvokeAI/archive/refs/tags" +INVOKE_AI_BRANCH = "https://github.com/invoke-ai/InvokeAI/archive/refs/heads" +INVOKE_AI_REL = "https://api.github.com/repos/invoke-ai/InvokeAI/releases" OS = platform.uname().system ARCH = platform.uname().machine @@ -29,34 +29,38 @@ if OS == "Windows": else: console = Console(style=Style(color="grey74", bgcolor="grey19")) -def get_versions()->dict: + +def get_versions() -> dict: return requests.get(url=INVOKE_AI_REL).json() -def invokeai_is_running()->bool: + +def invokeai_is_running() -> bool: for p in psutil.process_iter(): try: cmdline = p.cmdline() - matches = [x for x in cmdline if x.endswith(('invokeai','invokeai.exe'))] + matches = [x for x in cmdline if x.endswith(("invokeai", "invokeai.exe"))] if matches: - print(f':exclamation: [bold red]An InvokeAI instance appears to be running as process {p.pid}[/red bold]') + print( + f":exclamation: [bold red]An InvokeAI instance appears to be running as process {p.pid}[/red bold]" + ) return True - except (psutil.AccessDenied,psutil.NoSuchProcess): + except (psutil.AccessDenied, psutil.NoSuchProcess): continue return False + def welcome(versions: dict): - @group() def text(): - yield f'InvokeAI Version: [bold yellow]{__version__}' - yield '' - yield 'This script will update InvokeAI to the latest release, or to a development version of your choice.' - yield '' - yield '[bold yellow]Options:' - yield f'''[1] Update to the latest official release ([italic]{versions[0]['tag_name']}[/italic]) + yield f"InvokeAI Version: [bold yellow]{__version__}" + yield "" + yield "This script will update InvokeAI to the latest release, or to a development version of your choice." + yield "" + yield "[bold yellow]Options:" + yield f"""[1] Update to the latest official release ([italic]{versions[0]['tag_name']}[/italic]) [2] Update to the bleeding-edge development version ([italic]main[/italic]) [3] Manually enter the [bold]tag name[/bold] for the version you wish to update to -[4] Manually enter the [bold]branch name[/bold] for the version you wish to update to''' +[4] Manually enter the [bold]branch name[/bold] for the version you wish to update to""" console.rule() print( @@ -72,20 +76,22 @@ def welcome(versions: dict): ) console.line() + def get_extras(): - extras = '' + extras = "" try: - dist = pkg_resources.get_distribution('xformers') - extras = '[xformers]' + dist = pkg_resources.get_distribution("xformers") + extras = "[xformers]" except pkg_resources.DistributionNotFound: pass return extras + def main(): versions = get_versions() if invokeai_is_running(): - print(f':exclamation: [bold red]Please terminate all running instances of InvokeAI before updating.[/red bold]') - input('Press any key to continue...') + print(f":exclamation: [bold red]Please terminate all running instances of InvokeAI before updating.[/red bold]") + input("Press any key to continue...") return welcome(versions) @@ -93,36 +99,36 @@ def main(): tag = None branch = None release = None - choice = Prompt.ask('Choice:',choices=['1','2','3','4'],default='1') - - if choice=='1': - release = versions[0]['tag_name'] - elif choice=='2': - release = 'main' - elif choice=='3': - tag = Prompt.ask('Enter an InvokeAI tag name') - elif choice=='4': - branch = Prompt.ask('Enter an InvokeAI branch name') + choice = Prompt.ask("Choice:", choices=["1", "2", "3", "4"], default="1") + + if choice == "1": + release = versions[0]["tag_name"] + elif choice == "2": + release = "main" + elif choice == "3": + tag = Prompt.ask("Enter an InvokeAI tag name") + elif choice == "4": + branch = Prompt.ask("Enter an InvokeAI branch name") extras = get_extras() - print(f':crossed_fingers: Upgrading to [yellow]{tag if tag else release}[/yellow]') + print(f":crossed_fingers: Upgrading to [yellow]{tag if tag else release}[/yellow]") if release: cmd = f'pip install "invokeai{extras} @ {INVOKE_AI_SRC}/{release}.zip" --use-pep517 --upgrade' elif tag: cmd = f'pip install "invokeai{extras} @ {INVOKE_AI_TAG}/{tag}.zip" --use-pep517 --upgrade' else: cmd = f'pip install "invokeai{extras} @ {INVOKE_AI_BRANCH}/{branch}.zip" --use-pep517 --upgrade' - print('') - print('') - if os.system(cmd)==0: - print(f':heavy_check_mark: Upgrade successful') + print("") + print("") + if os.system(cmd) == 0: + print(f":heavy_check_mark: Upgrade successful") else: - print(f':exclamation: [bold red]Upgrade failed[/red bold]') - + print(f":exclamation: [bold red]Upgrade failed[/red bold]") + + if __name__ == "__main__": try: main() except KeyboardInterrupt: pass - diff --git a/invokeai/frontend/install/model_install.py b/invokeai/frontend/install/model_install.py index 5c90350ef0..ea9efe1908 100644 --- a/invokeai/frontend/install/model_install.py +++ b/invokeai/frontend/install/model_install.py @@ -56,18 +56,18 @@ logger = InvokeAILogger.getLogger() # build a table mapping all non-printable characters to None # for stripping control characters # from https://stackoverflow.com/questions/92438/stripping-non-printable-characters-from-a-string-in-python -NOPRINT_TRANS_TABLE = { - i: None for i in range(0, sys.maxunicode + 1) if not chr(i).isprintable() -} +NOPRINT_TRANS_TABLE = {i: None for i in range(0, sys.maxunicode + 1) if not chr(i).isprintable()} -def make_printable(s:str)->str: - '''Replace non-printable characters in a string''' + +def make_printable(s: str) -> str: + """Replace non-printable characters in a string""" return s.translate(NOPRINT_TRANS_TABLE) + class addModelsForm(CyclingForm, npyscreen.FormMultiPage): # for responsive resizing set to False, but this seems to cause a crash! FIX_MINIMUM_SIZE_WHEN_CREATED = True - + # for persistence current_tab = 0 @@ -82,24 +82,18 @@ class addModelsForm(CyclingForm, npyscreen.FormMultiPage): self.subprocess_connection = None if not config.model_conf_path.exists(): - with open(config.model_conf_path,'w') as file: - print('# InvokeAI model configuration file',file=file) + with open(config.model_conf_path, "w") as file: + print("# InvokeAI model configuration file", file=file) self.installer = ModelInstall(config) self.all_models = self.installer.all_models() self.starter_models = self.installer.starter_models() - self.model_labels = self._get_model_labels() + self.model_labels = self._get_model_labels() window_width, window_height = get_terminal_size() self.nextrely -= 1 self.add_widget_intelligent( npyscreen.FixedText, - value="Use ctrl-N and ctrl-P to move to the ext and

revious fields,", - editable=False, - color="CAUTION", - ) - self.add_widget_intelligent( - npyscreen.FixedText, - value="Use cursor arrows to make a selection, and space to toggle checkboxes.", + value="Use ctrl-N and ctrl-P to move to the ext and

revious fields. Cursor keys navigate, and selects.", editable=False, color="CAUTION", ) @@ -107,17 +101,17 @@ class addModelsForm(CyclingForm, npyscreen.FormMultiPage): self.tabs = self.add_widget_intelligent( SingleSelectColumns, values=[ - 'STARTER MODELS', - 'MORE MODELS', - 'CONTROLNETS', - 'LORA/LYCORIS', - 'TEXTUAL INVERSION', + "STARTER MODELS", + "MORE MODELS", + "CONTROLNETS", + "LORA/LYCORIS", + "TEXTUAL INVERSION", ], value=[self.current_tab], - columns = 5, - max_height = 2, + columns=5, + max_height=2, relx=8, - scroll_exit = True, + scroll_exit=True, ) self.tabs.on_changed = self._toggle_tables @@ -127,104 +121,105 @@ class addModelsForm(CyclingForm, npyscreen.FormMultiPage): self.nextrely = top_of_table self.pipeline_models = self.add_pipeline_widgets( - model_type=ModelType.Main, - window_width=window_width, - exclude = self.starter_models + model_type=ModelType.Main, window_width=window_width, exclude=self.starter_models ) # self.pipeline_models['autoload_pending'] = True - bottom_of_table = max(bottom_of_table,self.nextrely) + bottom_of_table = max(bottom_of_table, self.nextrely) self.nextrely = top_of_table self.controlnet_models = self.add_model_widgets( model_type=ModelType.ControlNet, window_width=window_width, ) - bottom_of_table = max(bottom_of_table,self.nextrely) + bottom_of_table = max(bottom_of_table, self.nextrely) self.nextrely = top_of_table self.lora_models = self.add_model_widgets( model_type=ModelType.Lora, window_width=window_width, ) - bottom_of_table = max(bottom_of_table,self.nextrely) + bottom_of_table = max(bottom_of_table, self.nextrely) self.nextrely = top_of_table self.ti_models = self.add_model_widgets( model_type=ModelType.TextualInversion, window_width=window_width, ) - bottom_of_table = max(bottom_of_table,self.nextrely) - - self.nextrely = bottom_of_table+1 + bottom_of_table = max(bottom_of_table, self.nextrely) + + self.nextrely = bottom_of_table + 1 self.monitor = self.add_widget_intelligent( BufferBox, - name='Log Messages', + name="Log Messages", editable=False, - max_height = 10, + max_height=8, ) - + self.nextrely += 1 done_label = "APPLY CHANGES" back_label = "BACK" + cancel_label = "CANCEL" + current_position = self.nextrely if self.multipage: self.back_button = self.add_widget_intelligent( npyscreen.ButtonPress, name=back_label, - rely=-3, when_pressed_function=self.on_back, ) else: + self.nextrely = current_position + self.cancel_button = self.add_widget_intelligent( + npyscreen.ButtonPress, name=cancel_label, when_pressed_function=self.on_cancel + ) + self.nextrely = current_position self.ok_button = self.add_widget_intelligent( npyscreen.ButtonPress, name=done_label, relx=(window_width - len(done_label)) // 2, - rely=-3, - when_pressed_function=self.on_execute + when_pressed_function=self.on_execute, ) label = "APPLY CHANGES & EXIT" + self.nextrely = current_position self.done = self.add_widget_intelligent( npyscreen.ButtonPress, name=label, - rely=-3, - relx=window_width-len(label)-15, + relx=window_width - len(label) - 15, when_pressed_function=self.on_done, ) # This restores the selected page on return from an installation - for i in range(1,self.current_tab+1): + for i in range(1, self.current_tab + 1): self.tabs.h_cursor_line_down(1) self._toggle_tables([self.current_tab]) - ############# diffusers tab ########## - def add_starter_pipelines(self)->dict[str, npyscreen.widget]: - '''Add widgets responsible for selecting diffusers models''' + ############# diffusers tab ########## + def add_starter_pipelines(self) -> dict[str, npyscreen.widget]: + """Add widgets responsible for selecting diffusers models""" widgets = dict() models = self.all_models starters = self.starter_models starter_model_labels = self.model_labels - - self.installed_models = sorted( - [x for x in starters if models[x].installed] - ) + + self.installed_models = sorted([x for x in starters if models[x].installed]) widgets.update( - label1 = self.add_widget_intelligent( + label1=self.add_widget_intelligent( CenteredTitleText, name="Select from a starter set of Stable Diffusion models from HuggingFace.", editable=False, labelColor="CAUTION", ) ) - + self.nextrely -= 1 # if user has already installed some initial models, then don't patronize them # by showing more recommendations - show_recommended = len(self.installed_models)==0 + show_recommended = len(self.installed_models) == 0 keys = [x for x in models.keys() if x in starters] widgets.update( - models_selected = self.add_widget_intelligent( + models_selected=self.add_widget_intelligent( MultiSelectColumns, columns=1, name="Install Starter Models", @@ -232,40 +227,43 @@ class addModelsForm(CyclingForm, npyscreen.FormMultiPage): value=[ keys.index(x) for x in keys - if (show_recommended and models[x].recommended) \ - or (x in self.installed_models) + if (show_recommended and models[x].recommended) or (x in self.installed_models) ], max_height=len(starters) + 1, relx=4, scroll_exit=True, ), - models = keys, + models=keys, ) self.nextrely += 1 return widgets ############# Add a set of model install widgets ######## - def add_model_widgets(self, - model_type: ModelType, - window_width: int=120, - install_prompt: str=None, - exclude: set=set(), - )->dict[str,npyscreen.widget]: - '''Generic code to create model selection widgets''' + def add_model_widgets( + self, + model_type: ModelType, + window_width: int = 120, + install_prompt: str = None, + exclude: set = set(), + ) -> dict[str, npyscreen.widget]: + """Generic code to create model selection widgets""" widgets = dict() - model_list = [x for x in self.all_models if self.all_models[x].model_type==model_type and not x in exclude] + model_list = [x for x in self.all_models if self.all_models[x].model_type == model_type and not x in exclude] model_labels = [self.model_labels[x] for x in model_list] - show_recommended = len(self.installed_models)==0 + show_recommended = len(self.installed_models) == 0 if len(model_list) > 0: max_width = max([len(x) for x in model_labels]) - columns = window_width // (max_width+8) # 8 characters for "[x] " and padding - columns = min(len(model_list),columns) or 1 - prompt = install_prompt or f"Select the desired {model_type.value.title()} models to install. Unchecked models will be purged from disk." + columns = window_width // (max_width + 8) # 8 characters for "[x] " and padding + columns = min(len(model_list), columns) or 1 + prompt = ( + install_prompt + or f"Select the desired {model_type.value.title()} models to install. Unchecked models will be purged from disk." + ) widgets.update( - label1 = self.add_widget_intelligent( + label1=self.add_widget_intelligent( CenteredTitleText, name=prompt, editable=False, @@ -274,7 +272,7 @@ class addModelsForm(CyclingForm, npyscreen.FormMultiPage): ) widgets.update( - models_selected = self.add_widget_intelligent( + models_selected=self.add_widget_intelligent( MultiSelectColumns, columns=columns, name=f"Install {model_type} Models", @@ -282,21 +280,20 @@ class addModelsForm(CyclingForm, npyscreen.FormMultiPage): value=[ model_list.index(x) for x in model_list - if (show_recommended and self.all_models[x].recommended) \ - or self.all_models[x].installed + if (show_recommended and self.all_models[x].recommended) or self.all_models[x].installed ], - max_height=len(model_list)//columns + 1, + max_height=len(model_list) // columns + 1, relx=4, scroll_exit=True, ), - models = model_list, + models=model_list, ) self.nextrely += 1 widgets.update( - download_ids = self.add_widget_intelligent( + download_ids=self.add_widget_intelligent( TextBox, - name = "Additional URLs, or HuggingFace repo_ids to install (Space separated. Use shift-control-V to paste):", + name="Additional URLs, or HuggingFace repo_ids to install (Space separated. Use shift-control-V to paste):", max_height=4, scroll_exit=True, editable=True, @@ -305,16 +302,17 @@ class addModelsForm(CyclingForm, npyscreen.FormMultiPage): return widgets ### Tab for arbitrary diffusers widgets ### - def add_pipeline_widgets(self, - model_type: ModelType=ModelType.Main, - window_width: int=120, - **kwargs, - )->dict[str,npyscreen.widget]: - '''Similar to add_model_widgets() but adds some additional widgets at the bottom - to support the autoload directory''' + def add_pipeline_widgets( + self, + model_type: ModelType = ModelType.Main, + window_width: int = 120, + **kwargs, + ) -> dict[str, npyscreen.widget]: + """Similar to add_model_widgets() but adds some additional widgets at the bottom + to support the autoload directory""" widgets = self.add_model_widgets( - model_type = model_type, - window_width = window_width, + model_type=model_type, + window_width=window_width, install_prompt=f"Additional {model_type.value.title()} models already installed.", **kwargs, ) @@ -323,7 +321,7 @@ class addModelsForm(CyclingForm, npyscreen.FormMultiPage): def resize(self): super().resize() - if (s := self.starter_pipelines.get("models_selected")): + if s := self.starter_pipelines.get("models_selected"): keys = [x for x in self.all_models.keys() if x in self.starter_models] s.values = [self.model_labels[x] for x in keys] @@ -338,27 +336,27 @@ class addModelsForm(CyclingForm, npyscreen.FormMultiPage): ] for group in widgets: - for k,v in group.items(): + for k, v in group.items(): try: v.hidden = True v.editable = False except: pass - for k,v in widgets[selected_tab].items(): + for k, v in widgets[selected_tab].items(): try: v.hidden = False - if not isinstance(v,(npyscreen.FixedText, npyscreen.TitleFixedText, CenteredTitleText)): + if not isinstance(v, (npyscreen.FixedText, npyscreen.TitleFixedText, CenteredTitleText)): v.editable = True except: pass self.__class__.current_tab = selected_tab # for persistence self.display() - def _get_model_labels(self) -> dict[str,str]: + def _get_model_labels(self) -> dict[str, str]: window_width, window_height = get_terminal_size() checkbox_width = 4 spacing_width = 2 - + models = self.all_models label_width = max([len(models[x].name) for x in models]) description_width = window_width - label_width - checkbox_width - spacing_width @@ -366,30 +364,28 @@ class addModelsForm(CyclingForm, npyscreen.FormMultiPage): result = dict() for x in models.keys(): description = models[x].description - description = description[0 : description_width - 3] + "..." \ - if description and len(description) > description_width \ - else description if description else '' - result[x] = f"%-{label_width}s %s" % (models[x].name, description) + description = ( + description[0 : description_width - 3] + "..." + if description and len(description) > description_width + else description + if description + else "" + ) + result[x] = f"%-{label_width}s %s" % (models[x].name, description) return result - + def _get_columns(self) -> int: window_width, window_height = get_terminal_size() - cols = ( - 4 - if window_width > 240 - else 3 - if window_width > 160 - else 2 - if window_width > 80 - else 1 - ) + cols = 4 if window_width > 240 else 3 if window_width > 160 else 2 if window_width > 80 else 1 return min(cols, len(self.installed_models)) - def confirm_deletions(self, selections: InstallSelections)->bool: + def confirm_deletions(self, selections: InstallSelections) -> bool: remove_models = selections.remove_models if len(remove_models) > 0: mods = "\n".join([ModelManager.parse_key(x)[0] for x in remove_models]) - return npyscreen.notify_ok_cancel(f"These unchecked models will be deleted from disk. Continue?\n---------\n{mods}") + return npyscreen.notify_ok_cancel( + f"These unchecked models will be deleted from disk. Continue?\n---------\n{mods}" + ) else: return True @@ -398,20 +394,20 @@ class addModelsForm(CyclingForm, npyscreen.FormMultiPage): app = self.parentApp if not self.confirm_deletions(app.install_selections): return - - self.monitor.entry_widget.buffer(['Processing...'],scroll_end=True) + + self.monitor.entry_widget.buffer(["Processing..."], scroll_end=True) self.ok_button.hidden = True self.display() - + # for communication with the subprocess parent_conn, child_conn = Pipe() p = Process( - target = process_and_execute, + target=process_and_execute, kwargs=dict( - opt = app.program_opts, - selections = app.install_selections, - conn_out = child_conn, - ) + opt=app.program_opts, + selections=app.install_selections, + conn_out=child_conn, + ), ) p.start() child_conn.close() @@ -428,7 +424,7 @@ class addModelsForm(CyclingForm, npyscreen.FormMultiPage): self.parentApp.setNextForm(None) self.parentApp.user_cancelled = True self.editing = False - + def on_done(self): self.marshall_arguments() if not self.confirm_deletions(self.parentApp.install_selections): @@ -436,75 +432,79 @@ class addModelsForm(CyclingForm, npyscreen.FormMultiPage): self.parentApp.setNextForm(None) self.parentApp.user_cancelled = False self.editing = False - + ########## This routine monitors the child process that is performing model installation and removal ##### def while_waiting(self): - '''Called during idle periods. Main task is to update the Log Messages box with messages - from the child process that does the actual installation/removal''' + """Called during idle periods. Main task is to update the Log Messages box with messages + from the child process that does the actual installation/removal""" c = self.subprocess_connection if not c: return - + monitor_widget = self.monitor.entry_widget while c.poll(): try: - data = c.recv_bytes().decode('utf-8') - data.strip('\n') + data = c.recv_bytes().decode("utf-8") + data.strip("\n") # processing child is requesting user input to select the # right configuration file - if data.startswith('*need v2 config'): - _,model_path,*_ = data.split(":",2) + if data.startswith("*need v2 config"): + _, model_path, *_ = data.split(":", 2) self._return_v2_config(model_path) # processing child is done - elif data=='*done*': + elif data == "*done*": self._close_subprocess_and_regenerate_form() break # update the log message box else: - data=make_printable(data) - data=data.replace('[A','') + data = make_printable(data) + data = data.replace("[A", "") monitor_widget.buffer( - textwrap.wrap(data, - width=monitor_widget.width, - subsequent_indent=' ', - ), - scroll_end=True + textwrap.wrap( + data, + width=monitor_widget.width, + subsequent_indent=" ", + ), + scroll_end=True, ) self.display() - except (EOFError,OSError): + except (EOFError, OSError): self.subprocess_connection = None - def _return_v2_config(self,model_path: str): + def _return_v2_config(self, model_path: str): c = self.subprocess_connection model_name = Path(model_path).name message = select_stable_diffusion_config_file(model_name=model_name) - c.send_bytes(message.encode('utf-8')) + c.send_bytes(message.encode("utf-8")) def _close_subprocess_and_regenerate_form(self): app = self.parentApp self.subprocess_connection.close() self.subprocess_connection = None - self.monitor.entry_widget.buffer(['** Action Complete **']) + self.monitor.entry_widget.buffer(["** Action Complete **"]) self.display() - + # rebuild the form, saving and restoring some of the fields that need to be preserved. saved_messages = self.monitor.entry_widget.values # autoload_dir = str(config.root_path / self.pipeline_models['autoload_directory'].value) # autoscan = self.pipeline_models['autoscan_on_startup'].value - + app.main_form = app.addForm( - "MAIN", addModelsForm, name="Install Stable Diffusion Models", multipage=self.multipage, + "MAIN", + addModelsForm, + name="Install Stable Diffusion Models", + multipage=self.multipage, ) app.switchForm("MAIN") - + app.main_form.monitor.entry_widget.values = saved_messages - app.main_form.monitor.entry_widget.buffer([''],scroll_end=True) + app.main_form.monitor.entry_widget.buffer([""], scroll_end=True) # app.main_form.pipeline_models['autoload_directory'].value = autoload_dir # app.main_form.pipeline_models['autoscan_on_startup'].value = autoscan - + def marshall_arguments(self): """ Assemble arguments and store as attributes of the application: @@ -519,21 +519,29 @@ class addModelsForm(CyclingForm, npyscreen.FormMultiPage): all_models = self.all_models # Defined models (in INITIAL_CONFIG.yaml or models.yaml) to add/remove - ui_sections = [self.starter_pipelines, self.pipeline_models, - self.controlnet_models, self.lora_models, self.ti_models] + ui_sections = [ + self.starter_pipelines, + self.pipeline_models, + self.controlnet_models, + self.lora_models, + self.ti_models, + ] for section in ui_sections: - if not 'models_selected' in section: + if not "models_selected" in section: continue - selected = set([section['models'][x] for x in section['models_selected'].value]) + selected = set([section["models"][x] for x in section["models_selected"].value]) models_to_install = [x for x in selected if not self.all_models[x].installed] - models_to_remove = [x for x in section['models'] if x not in selected and self.all_models[x].installed] + models_to_remove = [x for x in section["models"] if x not in selected and self.all_models[x].installed] selections.remove_models.extend(models_to_remove) - selections.install_models.extend(all_models[x].path or all_models[x].repo_id \ - for x in models_to_install if all_models[x].path or all_models[x].repo_id) + selections.install_models.extend( + all_models[x].path or all_models[x].repo_id + for x in models_to_install + if all_models[x].path or all_models[x].repo_id + ) # models located in the 'download_ids" section for section in ui_sections: - if downloads := section.get('download_ids'): + if downloads := section.get("download_ids"): selections.install_models.extend(downloads.value.split()) # load directory and whether to scan on startup @@ -542,8 +550,9 @@ class addModelsForm(CyclingForm, npyscreen.FormMultiPage): # self.parentApp.autoload_pending = False # selections.autoscan_on_startup = self.pipeline_models['autoscan_on_startup'].value + class AddModelApplication(npyscreen.NPSAppManaged): - def __init__(self,opt): + def __init__(self, opt): super().__init__() self.program_opts = opt self.user_cancelled = False @@ -553,76 +562,83 @@ class AddModelApplication(npyscreen.NPSAppManaged): def onStart(self): npyscreen.setTheme(npyscreen.Themes.DefaultTheme) self.main_form = self.addForm( - "MAIN", addModelsForm, name="Install Stable Diffusion Models", cycle_widgets=False, + "MAIN", + addModelsForm, + name="Install Stable Diffusion Models", + cycle_widgets=False, ) -class StderrToMessage(): + +class StderrToMessage: def __init__(self, connection: Connection): self.connection = connection - def write(self, data:str): - self.connection.send_bytes(data.encode('utf-8')) + def write(self, data: str): + self.connection.send_bytes(data.encode("utf-8")) def flush(self): pass + # -------------------------------------------------------- -def ask_user_for_prediction_type(model_path: Path, - tui_conn: Connection=None - )->SchedulerPredictionType: +def ask_user_for_prediction_type(model_path: Path, tui_conn: Connection = None) -> SchedulerPredictionType: if tui_conn: - logger.debug('Waiting for user response...') - return _ask_user_for_pt_tui(model_path, tui_conn) + logger.debug("Waiting for user response...") + return _ask_user_for_pt_tui(model_path, tui_conn) else: return _ask_user_for_pt_cmdline(model_path) -def _ask_user_for_pt_cmdline(model_path: Path)->SchedulerPredictionType: + +def _ask_user_for_pt_cmdline(model_path: Path) -> SchedulerPredictionType: choices = [SchedulerPredictionType.Epsilon, SchedulerPredictionType.VPrediction, None] print( -f""" + f""" Please select the type of the V2 checkpoint named {model_path.name}: [1] A model based on Stable Diffusion v2 trained on 512 pixel images (SD-2-base) [2] A model based on Stable Diffusion v2 trained on 768 pixel images (SD-2-768) [3] Skip this model and come back later. """ - ) + ) choice = None ok = False while not ok: try: - choice = input('select> ').strip() - choice = choices[int(choice)-1] + choice = input("select> ").strip() + choice = choices[int(choice) - 1] ok = True except (ValueError, IndexError): - print(f'{choice} is not a valid choice') + print(f"{choice} is not a valid choice") except EOFError: return return choice - -def _ask_user_for_pt_tui(model_path: Path, tui_conn: Connection)->SchedulerPredictionType: + + +def _ask_user_for_pt_tui(model_path: Path, tui_conn: Connection) -> SchedulerPredictionType: try: - tui_conn.send_bytes(f'*need v2 config for:{model_path}'.encode('utf-8')) + tui_conn.send_bytes(f"*need v2 config for:{model_path}".encode("utf-8")) # note that we don't do any status checking here - response = tui_conn.recv_bytes().decode('utf-8') + response = tui_conn.recv_bytes().decode("utf-8") if response is None: return None - elif response == 'epsilon': + elif response == "epsilon": return SchedulerPredictionType.epsilon - elif response == 'v': + elif response == "v": return SchedulerPredictionType.VPrediction - elif response == 'abort': - logger.info('Conversion aborted') + elif response == "abort": + logger.info("Conversion aborted") return None else: return response except: return None - + + # -------------------------------------------------------- -def process_and_execute(opt: Namespace, - selections: InstallSelections, - conn_out: Connection=None, - ): +def process_and_execute( + opt: Namespace, + selections: InstallSelections, + conn_out: Connection = None, +): # set up so that stderr is sent to conn_out if conn_out: translator = StderrToMessage(conn_out) @@ -632,66 +648,57 @@ def process_and_execute(opt: Namespace, logger.handlers.clear() logger.addHandler(logging.StreamHandler(translator)) - installer = ModelInstall(config, prediction_type_helper=lambda x: ask_user_for_prediction_type(x,conn_out)) + installer = ModelInstall(config, prediction_type_helper=lambda x: ask_user_for_prediction_type(x, conn_out)) installer.install(selections) if conn_out: - conn_out.send_bytes('*done*'.encode('utf-8')) + conn_out.send_bytes("*done*".encode("utf-8")) conn_out.close() -def do_listings(opt)->bool: + +def do_listings(opt) -> bool: """List installed models of various sorts, and return True if any were requested.""" model_manager = ModelManager(config.model_conf_path) - if opt.list_models == 'diffusers': + if opt.list_models == "diffusers": print("Diffuser models:") model_manager.print_models() - elif opt.list_models == 'controlnets': + elif opt.list_models == "controlnets": print("Installed Controlnet Models:") cnm = model_manager.list_controlnet_models() - print(textwrap.indent("\n".join([x for x in cnm if cnm[x]]),prefix=' ')) - elif opt.list_models == 'loras': + print(textwrap.indent("\n".join([x for x in cnm if cnm[x]]), prefix=" ")) + elif opt.list_models == "loras": print("Installed LoRA/LyCORIS Models:") cnm = model_manager.list_lora_models() - print(textwrap.indent("\n".join([x for x in cnm if cnm[x]]),prefix=' ')) - elif opt.list_models == 'tis': + print(textwrap.indent("\n".join([x for x in cnm if cnm[x]]), prefix=" ")) + elif opt.list_models == "tis": print("Installed Textual Inversion Embeddings:") cnm = model_manager.list_ti_models() - print(textwrap.indent("\n".join([x for x in cnm if cnm[x]]),prefix=' ')) + print(textwrap.indent("\n".join([x for x in cnm if cnm[x]]), prefix=" ")) else: return False return True + # -------------------------------------------------------- def select_and_download_models(opt: Namespace): - precision = ( - "float32" - if opt.full_precision - else choose_precision(torch.device(choose_torch_device())) - ) + precision = "float32" if opt.full_precision else choose_precision(torch.device(choose_torch_device())) config.precision = precision helper = lambda x: ask_user_for_prediction_type(x) # if do_listings(opt): # pass - + installer = ModelInstall(config, prediction_type_helper=helper) if opt.list_models: installer.list_models(opt.list_models) elif opt.add or opt.delete: - selections = InstallSelections( - install_models = opt.add or [], - remove_models = opt.delete or [] - ) + selections = InstallSelections(install_models=opt.add or [], remove_models=opt.delete or []) installer.install(selections) elif opt.default_only: - selections = InstallSelections( - install_models = installer.default_model() - ) + selections = InstallSelections(install_models=installer.default_model()) installer.install(selections) elif opt.yes_to_all: - selections = InstallSelections( - install_models = installer.recommended_models() - ) + selections = InstallSelections(install_models=installer.recommended_models()) installer.install(selections) # this is where the TUI is called @@ -706,15 +713,15 @@ def select_and_download_models(opt: Namespace): try: installApp.run() except KeyboardInterrupt as e: - if hasattr(installApp,'main_form'): - if installApp.main_form.subprocess \ - and installApp.main_form.subprocess.is_alive(): - logger.info('Terminating subprocesses') + if hasattr(installApp, "main_form"): + if installApp.main_form.subprocess and installApp.main_form.subprocess.is_alive(): + logger.info("Terminating subprocesses") installApp.main_form.subprocess.terminate() installApp.main_form.subprocess = None raise e process_and_execute(opt, installApp.install_selections) + # ------------------------------------- def main(): parser = argparse.ArgumentParser(description="InvokeAI model downloader") @@ -769,19 +776,17 @@ def main(): help="path to root of install directory", ) opt = parser.parse_args() - + invoke_args = [] if opt.root: - invoke_args.extend(['--root',opt.root]) + invoke_args.extend(["--root", opt.root]) if opt.full_precision: - invoke_args.extend(['--precision','float32']) + invoke_args.extend(["--precision", "float32"]) config.parse_args(invoke_args) logger = InvokeAILogger().getLogger(config=config) if not config.model_conf_path.exists(): - logger.info( - "Your InvokeAI root directory is not set up. Calling invokeai-configure." - ) + logger.info("Your InvokeAI root directory is not set up. Calling invokeai-configure.") from invokeai.frontend.install import invokeai_configure invokeai_configure() @@ -799,20 +804,18 @@ def main(): logger.info("Goodbye! Come back soon.") except widget.NotEnoughSpaceForWidget as e: if str(e).startswith("Height of 1 allocated"): - logger.error( - "Insufficient vertical space for the interface. Please make your window taller and try again" - ) - input('Press any key to continue...') + logger.error("Insufficient vertical space for the interface. Please make your window taller and try again") + input("Press any key to continue...") except Exception as e: if str(e).startswith("addwstr"): logger.error( "Insufficient horizontal space for the interface. Please make your window wider and try again." ) else: - print(f'An exception has occurred: {str(e)} Details:') + print(f"An exception has occurred: {str(e)} Details:") print(traceback.format_exc(), file=sys.stderr) - input('Press any key to continue...') - + input("Press any key to continue...") + # ------------------------------------- if __name__ == "__main__": diff --git a/invokeai/frontend/install/widgets.py b/invokeai/frontend/install/widgets.py index 82d3753eb4..10da15bf13 100644 --- a/invokeai/frontend/install/widgets.py +++ b/invokeai/frontend/install/widgets.py @@ -14,40 +14,42 @@ import textwrap import npyscreen.wgmultiline as wgmultiline from npyscreen import fmPopup from shutil import get_terminal_size -from curses import BUTTON2_CLICKED,BUTTON3_CLICKED +from curses import BUTTON2_CLICKED, BUTTON3_CLICKED # minimum size for UIs -MIN_COLS = 136 -MIN_LINES = 45 +MIN_COLS = 130 +MIN_LINES = 38 + # ------------------------------------- def set_terminal_size(columns: int, lines: int): ts = get_terminal_size() - width = max(columns,ts.columns) - height = max(lines,ts.lines) + width = max(columns, ts.columns) + height = max(lines, ts.lines) OS = platform.uname().system if OS == "Windows": pass # not working reliably - ask user to adjust the window - #_set_terminal_size_powershell(width,height) + # _set_terminal_size_powershell(width,height) elif OS in ["Darwin", "Linux"]: - _set_terminal_size_unix(width,height) + _set_terminal_size_unix(width, height) # check whether it worked.... ts = get_terminal_size() pause = False if ts.columns < columns: - print('\033[1mThis window is too narrow for the user interface. Please make it wider.\033[0m') + print("\033[1mThis window is too narrow for the user interface.\033[0m") pause = True if ts.lines < lines: - print('\033[1mThis window is too short for the user interface. Please make it taller.\033[0m') + print("\033[1mThis window is too short for the user interface.\033[0m") pause = True if pause: - input('Press any key to continue..') + input("Maximize the window then press any key to continue..") + def _set_terminal_size_powershell(width: int, height: int): - script=f''' + script = f""" $pshost = get-host $pswindow = $pshost.ui.rawui $newsize = $pswindow.buffersize @@ -58,8 +60,9 @@ $newsize = $pswindow.windowsize $newsize.height = {height} $newsize.width = {width} $pswindow.windowsize = $newsize -''' - subprocess.run(["powershell","-Command","-"],input=script,text=True) +""" + subprocess.run(["powershell", "-Command", "-"], input=script, text=True) + def _set_terminal_size_unix(width: int, height: int): import fcntl @@ -67,15 +70,16 @@ def _set_terminal_size_unix(width: int, height: int): # These terminals accept the size command and report that the # size changed, but they lie!!! - for bad_terminal in ['TERMINATOR_UUID', 'ALACRITTY_WINDOW_ID']: + for bad_terminal in ["TERMINATOR_UUID", "ALACRITTY_WINDOW_ID"]: if os.environ.get(bad_terminal): return - + winsize = struct.pack("HHHH", height, width, 0, 0) fcntl.ioctl(sys.stdout.fileno(), termios.TIOCSWINSZ, winsize) sys.stdout.write("\x1b[8;{height};{width}t".format(height=height, width=width)) sys.stdout.flush() + def set_min_terminal_size(min_cols: int, min_lines: int): # make sure there's enough room for the ui term_cols, term_lines = get_terminal_size() @@ -85,6 +89,7 @@ def set_min_terminal_size(min_cols: int, min_lines: int): lines = max(term_lines, min_lines) set_terminal_size(cols, lines) + class IntSlider(npyscreen.Slider): def translate_value(self): stri = "%2d / %2d" % (self.value, self.out_of) @@ -92,23 +97,25 @@ class IntSlider(npyscreen.Slider): stri = stri.rjust(l) return stri + # ------------------------------------- # fix npyscreen form so that cursor wraps both forward and backward class CyclingForm(object): def find_previous_editable(self, *args): done = False - n = self.editw-1 + n = self.editw - 1 while not done: if self._widgets__[n].editable and not self._widgets__[n].hidden: self.editw = n done = True n -= 1 - if n<0: + if n < 0: if self.cycle_widgets: - n = len(self._widgets__)-1 + n = len(self._widgets__) - 1 else: done = True - + + # ------------------------------------- class CenteredTitleText(npyscreen.TitleText): def __init__(self, *args, **keywords): @@ -159,7 +166,8 @@ class FloatSlider(npyscreen.Slider): class FloatTitleSlider(npyscreen.TitleText): _entry_type = FloatSlider -class SelectColumnBase(): + +class SelectColumnBase: def make_contained_widgets(self): self._my_widgets = [] column_width = self.width // self.columns @@ -217,11 +225,12 @@ class SelectColumnBase(): row_no = rel_y // self._contained_widget_height self.cursor_line = column_no * column_height + row_no if bstate & curses.BUTTON1_DOUBLE_CLICKED: - if hasattr(self,'on_mouse_double_click'): + if hasattr(self, "on_mouse_double_click"): self.on_mouse_double_click(self.cursor_line) self.display() -class MultiSelectColumns( SelectColumnBase, npyscreen.MultiSelect): + +class MultiSelectColumns(SelectColumnBase, npyscreen.MultiSelect): def __init__(self, screen, columns: int = 1, values: list = [], **keywords): self.columns = columns self.value_cnt = len(values) @@ -231,15 +240,17 @@ class MultiSelectColumns( SelectColumnBase, npyscreen.MultiSelect): def on_mouse_double_click(self, cursor_line): self.h_select_toggle(cursor_line) -class SingleSelectWithChanged(npyscreen.SelectOne): - def __init__(self,*args,**kwargs): - super().__init__(*args,**kwargs) - def h_select(self,ch): +class SingleSelectWithChanged(npyscreen.SelectOne): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def h_select(self, ch): super().h_select(ch) if self.on_changed: self.on_changed(self.value) + class SingleSelectColumns(SelectColumnBase, SingleSelectWithChanged): def __init__(self, screen, columns: int = 1, values: list = [], **keywords): self.columns = columns @@ -254,23 +265,25 @@ class SingleSelectColumns(SelectColumnBase, SingleSelectWithChanged): def when_cursor_moved(self): self.h_select(self.cursor_line) - def h_cursor_line_right(self,ch): - self.h_exit_down('bye bye') + def h_cursor_line_right(self, ch): + self.h_exit_down("bye bye") + class TextBoxInner(npyscreen.MultiLineEdit): - - def __init__(self,*args,**kwargs): - super().__init__(*args,**kwargs) + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) self.yank = None - self.handlers.update({ - "^A": self.h_cursor_to_start, - "^E": self.h_cursor_to_end, - "^K": self.h_kill, - "^F": self.h_cursor_right, - "^B": self.h_cursor_left, - "^Y": self.h_yank, - "^V": self.h_paste, - }) + self.handlers.update( + { + "^A": self.h_cursor_to_start, + "^E": self.h_cursor_to_end, + "^K": self.h_kill, + "^F": self.h_cursor_right, + "^B": self.h_cursor_left, + "^Y": self.h_yank, + "^V": self.h_paste, + } + ) def h_cursor_to_start(self, input): self.cursor_position = 0 @@ -279,27 +292,27 @@ class TextBoxInner(npyscreen.MultiLineEdit): self.cursor_position = len(self.value) def h_kill(self, input): - self.yank = self.value[self.cursor_position:] - self.value = self.value[:self.cursor_position] + self.yank = self.value[self.cursor_position :] + self.value = self.value[: self.cursor_position] def h_yank(self, input): if self.yank: self.paste(self.yank) def paste(self, text: str): - self.value = self.value[:self.cursor_position] + text + self.value[self.cursor_position:] + self.value = self.value[: self.cursor_position] + text + self.value[self.cursor_position :] self.cursor_position += len(text) - def h_paste(self, input: int=0): + def h_paste(self, input: int = 0): try: text = pyperclip.paste() except ModuleNotFoundError: text = "To paste with the mouse on Linux, please install the 'xclip' program." self.paste(text) - + def handle_mouse_event(self, mouse_event): mouse_id, rel_x, rel_y, z, bstate = self.interpret_mouse_event(mouse_event) - if bstate & (BUTTON2_CLICKED|BUTTON3_CLICKED): + if bstate & (BUTTON2_CLICKED | BUTTON3_CLICKED): self.h_paste() # def update(self, clear=True): @@ -320,77 +333,87 @@ class TextBoxInner(npyscreen.MultiLineEdit): # self.rely, self.relx + WIDTH, curses.ACS_VLINE, HEIGHT # ) - # # draw corners - # self.parent.curses_pad.addch( - # self.rely, - # self.relx, - # curses.ACS_ULCORNER, - # ) - # self.parent.curses_pad.addch( - # self.rely, - # self.relx + WIDTH, - # curses.ACS_URCORNER, - # ) - # self.parent.curses_pad.addch( - # self.rely + HEIGHT, - # self.relx, - # curses.ACS_LLCORNER, - # ) - # self.parent.curses_pad.addch( - # self.rely + HEIGHT, - # self.relx + WIDTH, - # curses.ACS_LRCORNER, - # ) + # # draw corners + # self.parent.curses_pad.addch( + # self.rely, + # self.relx, + # curses.ACS_ULCORNER, + # ) + # self.parent.curses_pad.addch( + # self.rely, + # self.relx + WIDTH, + # curses.ACS_URCORNER, + # ) + # self.parent.curses_pad.addch( + # self.rely + HEIGHT, + # self.relx, + # curses.ACS_LLCORNER, + # ) + # self.parent.curses_pad.addch( + # self.rely + HEIGHT, + # self.relx + WIDTH, + # curses.ACS_LRCORNER, + # ) + + # # fool our superclass into thinking drawing area is smaller - this is really hacky but it seems to work + # (relx, rely, height, width) = (self.relx, self.rely, self.height, self.width) + # self.relx += 1 + # self.rely += 1 + # self.height -= 1 + # self.width -= 1 + # super().update(clear=False) + # (self.relx, self.rely, self.height, self.width) = (relx, rely, height, width) - # # fool our superclass into thinking drawing area is smaller - this is really hacky but it seems to work - # (relx, rely, height, width) = (self.relx, self.rely, self.height, self.width) - # self.relx += 1 - # self.rely += 1 - # self.height -= 1 - # self.width -= 1 - # super().update(clear=False) - # (self.relx, self.rely, self.height, self.width) = (relx, rely, height, width) class TextBox(npyscreen.BoxTitle): _contained_widget = TextBoxInner + class BufferBox(npyscreen.BoxTitle): _contained_widget = npyscreen.BufferPager + class ConfirmCancelPopup(fmPopup.ActionPopup): DEFAULT_COLUMNS = 100 + def on_ok(self): self.value = True + def on_cancel(self): self.value = False - + + class FileBox(npyscreen.BoxTitle): _contained_widget = npyscreen.Filename - + + class PrettyTextBox(npyscreen.BoxTitle): _contained_widget = TextBox - + + def _wrap_message_lines(message, line_length): lines = [] - for line in message.split('\n'): + for line in message.split("\n"): lines.extend(textwrap.wrap(line.rstrip(), line_length)) return lines - + + def _prepare_message(message): if isinstance(message, list) or isinstance(message, tuple): - return "\n".join([ s.rstrip() for s in message]) - #return "\n".join(message) + return "\n".join([s.rstrip() for s in message]) + # return "\n".join(message) else: return message - + + def select_stable_diffusion_config_file( - form_color: str='DANGER', - wrap:bool =True, - model_name:str='Unknown', + form_color: str = "DANGER", + wrap: bool = True, + model_name: str = "Unknown", ): message = f"Please select the correct base model for the V2 checkpoint named '{model_name}'. Press to skip installation." title = "CONFIG FILE SELECTION" - options=[ + options = [ "An SD v2.x base model (512 pixels; no 'parameterization:' line in its yaml file)", "An SD v2.x v-predictive model (768 pixels; 'parameterization: \"v\"' line in its yaml file)", "Skip installation for now and come back later", @@ -403,22 +426,22 @@ def select_stable_diffusion_config_file( lines=16, ) F.preserve_selected_widget = True - + mlw = F.add( wgmultiline.Pager, max_height=4, editable=False, ) - mlw_width = mlw.width-1 + mlw_width = mlw.width - 1 if wrap: message = _wrap_message_lines(message, mlw_width) mlw.values = message choice = F.add( npyscreen.SelectOne, - values = options, - value = [0], - max_height = len(options)+1, + values=options, + value=[0], + max_height=len(options) + 1, scroll_exit=True, ) @@ -426,6 +449,6 @@ def select_stable_diffusion_config_file( F.edit() if not F.value: return None - assert choice.value[0] in range(0,3),'invalid choice' - choices = ['epsilon','v','abort'] + assert choice.value[0] in range(0, 3), "invalid choice" + choices = ["epsilon", "v", "abort"] return choices[choice.value[0]] diff --git a/invokeai/frontend/legacy_launch_invokeai.py b/invokeai/frontend/legacy_launch_invokeai.py index 349fa5b945..e4509db6e5 100644 --- a/invokeai/frontend/legacy_launch_invokeai.py +++ b/invokeai/frontend/legacy_launch_invokeai.py @@ -2,18 +2,22 @@ import os import sys import argparse + def main(): parser = argparse.ArgumentParser() - parser.add_argument('--web', action='store_true') - opts,_ = parser.parse_known_args() + parser.add_argument("--web", action="store_true") + opts, _ = parser.parse_known_args() if opts.web: - sys.argv.pop(sys.argv.index('--web')) + sys.argv.pop(sys.argv.index("--web")) from invokeai.app.api_app import invoke_api + invoke_api() else: from invokeai.app.cli_app import invoke_cli + invoke_cli() -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/invokeai/frontend/merge/__init__.py b/invokeai/frontend/merge/__init__.py index f1fc66c39e..3a2e4474a5 100644 --- a/invokeai/frontend/merge/__init__.py +++ b/invokeai/frontend/merge/__init__.py @@ -2,4 +2,3 @@ Initialization file for invokeai.frontend.merge """ from .merge_diffusers import main as invokeai_merge_diffusers - diff --git a/invokeai/frontend/merge/merge_diffusers.py b/invokeai/frontend/merge/merge_diffusers.py index c20d913883..81a7b3f6c8 100644 --- a/invokeai/frontend/merge/merge_diffusers.py +++ b/invokeai/frontend/merge/merge_diffusers.py @@ -20,13 +20,17 @@ from omegaconf import OmegaConf import invokeai.backend.util.logging as logger from invokeai.app.services.config import InvokeAIAppConfig from invokeai.backend.model_management import ( - ModelMerger, MergeInterpolationMethod, - ModelManager, ModelType, BaseModelType, + ModelMerger, + MergeInterpolationMethod, + ModelManager, + ModelType, + BaseModelType, ) from invokeai.frontend.install.widgets import FloatTitleSlider, TextBox, SingleSelectColumns config = InvokeAIAppConfig.get_config() + def _parse_args() -> Namespace: parser = argparse.ArgumentParser(description="InvokeAI model merging") parser.add_argument( @@ -134,14 +138,14 @@ class mergeModelsForm(npyscreen.FormMultiPageAction): self.base_select = self.add_widget_intelligent( SingleSelectColumns, values=[ - 'Models Built on SD-1.x', - 'Models Built on SD-2.x', + "Models Built on SD-1.x", + "Models Built on SD-2.x", ], value=[self.current_base], - columns = 4, - max_height = 2, + columns=4, + max_height=2, relx=8, - scroll_exit = True, + scroll_exit=True, ) self.base_select.on_changed = self._populate_models self.add_widget_intelligent( @@ -300,15 +304,11 @@ class mergeModelsForm(npyscreen.FormMultiPageAction): def validate_field_values(self) -> bool: bad_fields = [] model_names = self.model_names - selected_models = set( - (model_names[self.model1.value[0]], model_names[self.model2.value[0]]) - ) + selected_models = set((model_names[self.model1.value[0]], model_names[self.model2.value[0]])) if self.model3.value[0] > 0: selected_models.add(model_names[self.model3.value[0] - 1]) if len(selected_models) < 2: - bad_fields.append( - f"Please select two or three DIFFERENT models to compare. You selected {selected_models}" - ) + bad_fields.append(f"Please select two or three DIFFERENT models to compare. You selected {selected_models}") if len(bad_fields) > 0: message = "The following problems were detected and must be corrected:" for problem in bad_fields: @@ -318,7 +318,7 @@ class mergeModelsForm(npyscreen.FormMultiPageAction): else: return True - def get_model_names(self, base_model: BaseModelType=None) -> List[str]: + def get_model_names(self, base_model: BaseModelType = None) -> List[str]: model_names = [ info["name"] for info in self.model_manager.list_models(model_type=ModelType.Main, base_model=base_model) @@ -326,20 +326,21 @@ class mergeModelsForm(npyscreen.FormMultiPageAction): ] return sorted(model_names) - def _populate_models(self,value=None): + def _populate_models(self, value=None): base_model = tuple(BaseModelType)[value[0]] self.model_names = self.get_model_names(base_model) - + models_plus_none = self.model_names.copy() models_plus_none.insert(0, "None") self.model1.values = self.model_names self.model2.values = self.model_names self.model3.values = models_plus_none - + self.display() + class Mergeapp(npyscreen.NPSAppManaged): - def __init__(self, model_manager:ModelManager): + def __init__(self, model_manager: ModelManager): super().__init__() self.model_manager = model_manager @@ -367,9 +368,7 @@ def run_cli(args: Namespace): if not args.merged_model_name: args.merged_model_name = "+".join(args.model_names) - logger.info( - f'No --merged_model_name provided. Defaulting to "{args.merged_model_name}"' - ) + logger.info(f'No --merged_model_name provided. Defaulting to "{args.merged_model_name}"') model_manager = ModelManager(config.model_conf_path) assert ( @@ -383,7 +382,7 @@ def run_cli(args: Namespace): def main(): args = _parse_args() - config.parse_args(['--root',str(args.root_dir)]) + config.parse_args(["--root", str(args.root_dir)]) try: if args.front_end: @@ -392,13 +391,9 @@ def main(): run_cli(args) except widget.NotEnoughSpaceForWidget as e: if str(e).startswith("Height of 1 allocated"): - logger.error( - "You need to have at least two diffusers models defined in models.yaml in order to merge" - ) + logger.error("You need to have at least two diffusers models defined in models.yaml in order to merge") else: - logger.error( - "Not enough room for the user interface. Try making this window larger." - ) + logger.error("Not enough room for the user interface. Try making this window larger.") sys.exit(-1) except Exception as e: logger.error(e) diff --git a/invokeai/frontend/training/textual_inversion.py b/invokeai/frontend/training/textual_inversion.py index e1c7b3749f..25debf4bdc 100755 --- a/invokeai/frontend/training/textual_inversion.py +++ b/invokeai/frontend/training/textual_inversion.py @@ -23,16 +23,14 @@ from omegaconf import OmegaConf import invokeai.backend.util.logging as logger from invokeai.app.services.config import InvokeAIAppConfig -from ...backend.training import ( - do_textual_inversion_training, - parse_args -) +from ...backend.training import do_textual_inversion_training, parse_args TRAINING_DATA = "text-inversion-training-data" TRAINING_DIR = "text-inversion-output" CONF_FILE = "preferences.conf" config = None + class textualInversionForm(npyscreen.FormMultiPageAction): resolutions = [512, 768, 1024] lr_schedulers = [ @@ -111,9 +109,7 @@ class textualInversionForm(npyscreen.FormMultiPageAction): npyscreen.TitleSelectOne, name="Learnable property:", values=self.learnable_properties, - value=self.learnable_properties.index( - saved_args.get("learnable_property", "object") - ), + value=self.learnable_properties.index(saved_args.get("learnable_property", "object")), max_height=4, scroll_exit=True, ) @@ -243,9 +239,7 @@ class textualInversionForm(npyscreen.FormMultiPageAction): def initializer_changed(self): placeholder = self.placeholder_token.value self.prompt_token.value = f"(Trigger by using <{placeholder}> in your prompts)" - self.train_data_dir.value = str( - config.root_dir / TRAINING_DATA / placeholder - ) + self.train_data_dir.value = str(config.root_dir / TRAINING_DATA / placeholder) self.output_dir.value = str(config.root_dir / TRAINING_DIR / placeholder) self.resume_from_checkpoint.value = Path(self.output_dir.value).exists() @@ -254,9 +248,7 @@ class textualInversionForm(npyscreen.FormMultiPageAction): self.parentApp.setNextForm(None) self.editing = False self.parentApp.ti_arguments = self.marshall_arguments() - npyscreen.notify( - "Launching textual inversion training. This will take a while..." - ) + npyscreen.notify("Launching textual inversion training. This will take a while...") else: self.editing = True @@ -266,13 +258,9 @@ class textualInversionForm(npyscreen.FormMultiPageAction): def validate_field_values(self) -> bool: bad_fields = [] if self.model.value is None: - bad_fields.append( - "Model Name must correspond to a known model in models.yaml" - ) + bad_fields.append("Model Name must correspond to a known model in models.yaml") if not re.match("^[a-zA-Z0-9.-]+$", self.placeholder_token.value): - bad_fields.append( - "Trigger term must only contain alphanumeric characters, the dot and hyphen" - ) + bad_fields.append("Trigger term must only contain alphanumeric characters, the dot and hyphen") if self.train_data_dir.value is None: bad_fields.append("Data Training Directory cannot be empty") if self.output_dir.value is None: @@ -288,16 +276,8 @@ class textualInversionForm(npyscreen.FormMultiPageAction): def get_model_names(self) -> Tuple[List[str], int]: conf = OmegaConf.load(config.root_dir / "configs/models.yaml") - model_names = [ - idx - for idx in sorted(list(conf.keys())) - if conf[idx].get("format", None) == "diffusers" - ] - defaults = [ - idx - for idx in range(len(model_names)) - if "default" in conf[model_names[idx]] - ] + model_names = [idx for idx in sorted(list(conf.keys())) if conf[idx].get("format", None) == "diffusers"] + defaults = [idx for idx in range(len(model_names)) if "default" in conf[model_names[idx]]] default = defaults[0] if len(defaults) > 0 else 0 return (model_names, default) @@ -310,9 +290,7 @@ class textualInversionForm(npyscreen.FormMultiPageAction): resolution=self.resolutions[self.resolution.value[0]], lr_scheduler=self.lr_schedulers[self.lr_scheduler.value[0]], mixed_precision=self.precisions[self.mixed_precision.value[0]], - learnable_property=self.learnable_properties[ - self.learnable_property.value[0] - ], + learnable_property=self.learnable_properties[self.learnable_property.value[0]], ) # all the strings and booleans @@ -374,9 +352,7 @@ def copy_to_embeddings_folder(args: dict): os.makedirs(destination, exist_ok=True) logger.info(f"Training completed. Copying learned_embeds.bin into {str(destination)}") shutil.copy(source, destination) - if ( - input("Delete training logs and intermediate checkpoints? [y] ") or "y" - ).startswith(("y", "Y")): + if (input("Delete training logs and intermediate checkpoints? [y] ") or "y").startswith(("y", "Y")): shutil.rmtree(Path(args["output_dir"])) else: logger.info(f'Keeping {args["output_dir"]}') @@ -423,7 +399,7 @@ def do_front_end(args: Namespace): save_args(args) try: - do_textual_inversion_training(InvokeAIAppConfig.get_config(),**args) + do_textual_inversion_training(InvokeAIAppConfig.get_config(), **args) copy_to_embeddings_folder(args) except Exception as e: logger.error("An exception occurred during training. The exception was:") @@ -434,19 +410,19 @@ def do_front_end(args: Namespace): def main(): global config - + args = parse_args() config = InvokeAIAppConfig.get_config() # change root if needed if args.root_dir: config.root = args.root_dir - + try: if args.front_end: do_front_end(args) else: - do_textual_inversion_training(config,**vars(args)) + do_textual_inversion_training(config, **vars(args)) except AssertionError as e: logger.error(e) sys.exit(-1) @@ -454,13 +430,9 @@ def main(): pass except (widget.NotEnoughSpaceForWidget, Exception) as e: if str(e).startswith("Height of 1 allocated"): - logger.error( - "You need to have at least one diffusers models defined in models.yaml in order to train" - ) + logger.error("You need to have at least one diffusers models defined in models.yaml in order to train") elif str(e).startswith("addwstr"): - logger.error( - "Not enough window space for the interface. Please make your window larger and try again." - ) + logger.error("Not enough window space for the interface. Please make your window larger and try again.") else: logger.error(e) sys.exit(-1) diff --git a/invokeai/frontend/web/__init__.py b/invokeai/frontend/web/__init__.py index 010129ece2..e9758b27b6 100644 --- a/invokeai/frontend/web/__init__.py +++ b/invokeai/frontend/web/__init__.py @@ -1,3 +1,3 @@ -''' +""" Initialization file for invokeai.frontend.web -''' +""" diff --git a/invokeai/frontend/web/dist/assets/App-69e5ea36.js b/invokeai/frontend/web/dist/assets/App-69e5ea36.js new file mode 100644 index 0000000000..a87a1119a7 --- /dev/null +++ b/invokeai/frontend/web/dist/assets/App-69e5ea36.js @@ -0,0 +1,169 @@ +import{t as cv,r as Q8,i as uv,a as Rc,b as h_,S as m_,c as g_,d as v_,e as dv,f as b_,g as fv,h as J8,j as Z8,k as eR,l as tR,m as y_,n as nR,o as rR,p as oR,q as x_,s as sR,u as aR,v as iR,w as lR,x as cR,y as uR,z as f,A as i,B as Qh,C as Ip,D as dR,E as w_,F as S_,G as fR,P as id,H as M1,I as pR,J as hR,K as mR,L as gR,M as vR,N as bR,O as yR,Q as P2,R as Te,T as xR,U as Ie,V as kt,W as et,X as ld,Y as Fo,Z as Xr,_ as Br,$ as qn,a0 as dl,a1 as $a,a2 as tn,a3 as ns,a4 as Zl,a5 as za,a6 as Jh,a7 as D1,a8 as cd,a9 as or,aa as wR,ab as F,ac as C_,ad as j2,ae as k_,af as pv,ag as Mc,ah as SR,ai as __,aj as P_,ak as Dc,al as CR,am as fe,an as Ge,ao as Qt,ap as z,aq as kR,ar as I2,as as _R,at as PR,au as E2,av as te,aw as jR,ax as Dn,ay as Bn,az as Oe,aA as H,aB as Xs,aC as Ye,aD as Kn,aE as j_,aF as I_,aG as E_,aH as _i,aI as Ds,aJ as T1,aK as IR,aL as ER,aM as OR,aN as Rl,aO as xu,aP as RR,aQ as MR,aR as DR,aS as TR,aT as AR,aU as O2,aV as ui,aW as A1,aX as Ep,aY as Zh,aZ as O_,a_ as os,a$ as R_,b0 as NR,b1 as Tc,b2 as M_,b3 as D_,b4 as Es,b5 as _o,b6 as wu,b7 as $R,b8 as zR,b9 as LR,ba as BR,bb as N1,bc as Op,bd as FR,be as HR,bf as If,bg as Ef,bh as Ru,bi as Mu,bj as R2,bk as Rp,bl as M2,bm as Mp,bn as D2,bo as hv,bp as T2,bq as mv,br as A2,bs as Dp,bt as N2,bu as hc,bv as $2,bw as mc,bx as z2,by as Tp,bz as $1,bA as z1,bB as T_,bC as L1,bD as B1,bE as WR,bF as VR,bG as em,bH as ql,bI as UR,bJ as GR,bK as vp,bL as qR,bM as KR,bN as YR,bO as gv,bP as A_,bQ as XR,bR as N_,bS as $_,bT as ss,bU as L2,bV as La,bW as QR,bX as vv,bY as JR,bZ as z_,b_ as B2,b$ as ZR,c0 as eM,c1 as tM,c2 as nM,c3 as rM,c4 as oM,c5 as F1,c6 as H1,c7 as sM,c8 as Ln,c9 as F2,ca as L_,cb as aM,cc as iM,cd as lM,ce as cM,cf as uM,cg as dM,ch as fM,ci as pM,cj as hM,ck as B_,cl as mM,cm as gM,cn as vM,co as bM,cp as yM,cq as xM,cr as wM,cs as SM,ct as CM,cu as kM,cv as jo,cw as vr,cx as _M,cy as W1,cz as ud,cA as dd,cB as PM,cC as H2,cD as jM,cE as W2,cF as IM,cG as EM,cH as OM,cI as RM,cJ as V2,cK as U2,cL as na,cM as V1,cN as G2,cO as q2,cP as tm,cQ as MM,cR as DM,cS as TM,cT as AM,cU as K2,cV as Y2,cW as NM,cX as X2,cY as $M,cZ as F_,c_ as Q2,c$ as zM,d0 as LM,d1 as Ss,d2 as BM,d3 as FM,d4 as H_,d5 as W_,d6 as HM,d7 as J2,d8 as WM,d9 as VM,da as V_,db as UM,dc as GM,dd as qM,de as KM,df as YM,dg as XM,dh as QM,di as U_,dj as JM,dk as G_,dl as Z2,dm as Of,dn as ZM,dp as U1,dq as q_,dr as e7,ds as t7,dt as n7,du as ls,dv as r7,dw as o7,dx as s7,dy as a7,dz as i7,dA as l7,dB as c7,dC as u7,dD as d7,dE as f7,dF as p7,dG as h7,dH as m7,dI as g7,dJ as ew,dK as tw,dL as v7,dM as K_,dN as Y_,dO as fd,dP as X_,dQ as Hu,dR as Q_,dS as nw,dT as b7,dU as y7,dV as J_,dW as x7,dX as G1,dY as rw,dZ as Z_,d_ as w7,d$ as ow,e0 as e3,e1 as Ts,e2 as S7,e3 as t3,e4 as sw,e5 as C7,e6 as k7,e7 as _7,e8 as P7,e9 as j7,ea as I7,eb as E7,ec as O7,ed as R7,ee as M7,ef as D7,eg as T7,eh as A7,ei as N7,ej as $7,ek as z7,el as L7,em as B7,en as F7,eo as H7,ep as aw,eq as bp,er as W7,es as Ap,et as n3,eu as Wu,ev as V7,ew as U7,ex as ea,ey as r3,ez as q1,eA as pd,eB as G7,eC as q7,eD as K7,eE as Ia,eF as o3,eG as Y7,eH as X7,eI as s3,eJ as Q7,eK as J7,eL as Z7,eM as eD,eN as tD,eO as nD,eP as rD,eQ as oD,eR as sD,eS as aD,eT as iw,eU as iD,eV as lD,eW as cD,eX as uD,eY as dD,eZ as fD,e_ as pD,e$ as hD,f0 as a0,f1 as Js,f2 as i0,f3 as l0,f4 as Rf,f5 as lw,f6 as bv,f7 as mD,f8 as gD,f9 as vD,fa as bD,fb as Np,fc as a3,fd as i3,fe as yD,ff as xD,fg as l3,fh as c3,fi as u3,fj as d3,fk as f3,fl as p3,fm as h3,fn as m3,fo as ec,fp as tc,fq as g3,fr as v3,fs as wD,ft as b3,fu as y3,fv as x3,fw as w3,fx as S3,fy as C3,fz as K1,fA as SD,fB as cw,fC as CD,fD as kD,fE as $p,fF as uw,fG as dw,fH as fw,fI as pw,fJ as _D,fK as PD,fL as jD,fM as ID,fN as ED,fO as OD,fP as RD,fQ as MD,fR as DD}from"./index-89941396.js";import{I as Kr,u as TD,c as AD,a as Rn,b as rr,d as Ba,P as Vu,C as ND,e as be,m as nm,f as k3,g as Fa,h as $D,r as Ue,i as zD,j as hw,k as Wt,l as Sr}from"./MantineProvider-8184f020.js";function LD(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,s;for(s=0;s=0)&&(n[o]=e[o]);return n}var mw=1/0,BD=17976931348623157e292;function c0(e){if(!e)return e===0?e:0;if(e=cv(e),e===mw||e===-mw){var t=e<0?-1:1;return t*BD}return e===e?e:0}var FD=function(){return Q8.Date.now()};const u0=FD;var HD="Expected a function",WD=Math.max,VD=Math.min;function UD(e,t,n){var r,o,s,a,c,d,p=0,h=!1,m=!1,v=!0;if(typeof e!="function")throw new TypeError(HD);t=cv(t)||0,uv(n)&&(h=!!n.leading,m="maxWait"in n,s=m?WD(cv(n.maxWait)||0,t):s,v="trailing"in n?!!n.trailing:v);function b(O){var R=r,M=o;return r=o=void 0,p=O,a=e.apply(M,R),a}function w(O){return p=O,c=setTimeout(k,t),h?b(O):a}function y(O){var R=O-d,M=O-p,T=t-R;return m?VD(T,s-M):T}function S(O){var R=O-d,M=O-p;return d===void 0||R>=t||R<0||m&&M>=s}function k(){var O=u0();if(S(O))return _(O);c=setTimeout(k,y(O))}function _(O){return c=void 0,v&&r?b(O):(r=o=void 0,a)}function I(){c!==void 0&&clearTimeout(c),p=0,r=d=o=c=void 0}function P(){return c===void 0?a:_(u0())}function E(){var O=u0(),R=S(O);if(r=arguments,o=this,d=O,R){if(c===void 0)return w(d);if(m)return clearTimeout(c),c=setTimeout(k,t),b(d)}return c===void 0&&(c=setTimeout(k,t)),a}return E.cancel=I,E.flush=P,E}var GD=200;function qD(e,t,n,r){var o=-1,s=g_,a=!0,c=e.length,d=[],p=t.length;if(!c)return d;n&&(t=Rc(t,h_(n))),r?(s=v_,a=!1):t.length>=GD&&(s=dv,a=!1,t=new m_(t));e:for(;++o=120&&h.length>=120)?new m_(a&&h):void 0}h=e[0];var m=-1,v=c[0];e:for(;++m{r.has(s)&&n(o,s)})}const _3=({id:e,x:t,y:n,width:r,height:o,style:s,color:a,strokeColor:c,strokeWidth:d,className:p,borderRadius:h,shapeRendering:m,onClick:v})=>{const{background:b,backgroundColor:w}=s||{},y=a||b||w;return i.jsx("rect",{className:Qh(["react-flow__minimap-node",p]),x:t,y:n,rx:h,ry:h,width:r,height:o,fill:y,stroke:c,strokeWidth:d,shapeRendering:m,onClick:v?S=>v(S,e):void 0})};_3.displayName="MiniMapNode";var pT=f.memo(_3);const hT=e=>e.nodeOrigin,mT=e=>e.getNodes().filter(t=>!t.hidden&&t.width&&t.height),d0=e=>e instanceof Function?e:()=>e;function gT({nodeStrokeColor:e="transparent",nodeColor:t="#e2e2e2",nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:o=2,nodeComponent:s=pT,onClick:a}){const c=Ip(mT,M1),d=Ip(hT),p=d0(t),h=d0(e),m=d0(n),v=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return i.jsx(i.Fragment,{children:c.map(b=>{const{x:w,y}=dR(b,d).positionAbsolute;return i.jsx(s,{x:w,y,width:b.width,height:b.height,style:b.style,className:m(b),color:p(b),borderRadius:r,strokeColor:h(b),strokeWidth:o,shapeRendering:v,onClick:a,id:b.id},b.id)})})}var vT=f.memo(gT);const bT=200,yT=150,xT=e=>{const t=e.getNodes(),n={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};return{viewBB:n,boundingRect:t.length>0?mR(gR(t,e.nodeOrigin),n):n,rfId:e.rfId}},wT="react-flow__minimap-desc";function P3({style:e,className:t,nodeStrokeColor:n="transparent",nodeColor:r="#e2e2e2",nodeClassName:o="",nodeBorderRadius:s=5,nodeStrokeWidth:a=2,nodeComponent:c,maskColor:d="rgb(240, 240, 240, 0.6)",maskStrokeColor:p="none",maskStrokeWidth:h=1,position:m="bottom-right",onClick:v,onNodeClick:b,pannable:w=!1,zoomable:y=!1,ariaLabel:S="React Flow mini map",inversePan:k=!1,zoomStep:_=10}){const I=w_(),P=f.useRef(null),{boundingRect:E,viewBB:O,rfId:R}=Ip(xT,M1),M=(e==null?void 0:e.width)??bT,T=(e==null?void 0:e.height)??yT,A=E.width/M,$=E.height/T,Q=Math.max(A,$),B=Q*M,V=Q*T,q=5*Q,G=E.x-(B-E.width)/2-q,D=E.y-(V-E.height)/2-q,L=B+q*2,W=V+q*2,Y=`${wT}-${R}`,ae=f.useRef(0);ae.current=Q,f.useEffect(()=>{if(P.current){const X=S_(P.current),K=re=>{const{transform:oe,d3Selection:pe,d3Zoom:le}=I.getState();if(re.sourceEvent.type!=="wheel"||!pe||!le)return;const ge=-re.sourceEvent.deltaY*(re.sourceEvent.deltaMode===1?.05:re.sourceEvent.deltaMode?1:.002)*_,_e=oe[2]*Math.pow(2,ge);le.scaleTo(pe,_e)},U=re=>{const{transform:oe,d3Selection:pe,d3Zoom:le,translateExtent:ge,width:_e,height:ie}=I.getState();if(re.sourceEvent.type!=="mousemove"||!pe||!le)return;const Se=ae.current*Math.max(1,oe[2])*(k?-1:1),Fe={x:oe[0]-re.sourceEvent.movementX*Se,y:oe[1]-re.sourceEvent.movementY*Se},Ae=[[0,0],[_e,ie]],He=pR.translate(Fe.x,Fe.y).scale(oe[2]),Ct=le.constrain()(He,Ae,ge);le.transform(pe,Ct)},se=fR().on("zoom",w?U:null).on("zoom.wheel",y?K:null);return X.call(se),()=>{X.on("zoom",null)}}},[w,y,k,_]);const ye=v?X=>{const K=hR(X);v(X,{x:K[0],y:K[1]})}:void 0,ue=b?(X,K)=>{const U=I.getState().nodeInternals.get(K);b(X,U)}:void 0;return i.jsx(id,{position:m,style:e,className:Qh(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:i.jsxs("svg",{width:M,height:T,viewBox:`${G} ${D} ${L} ${W}`,role:"img","aria-labelledby":Y,ref:P,onClick:ye,children:[S&&i.jsx("title",{id:Y,children:S}),i.jsx(vT,{onClick:ue,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:s,nodeClassName:o,nodeStrokeWidth:a,nodeComponent:c}),i.jsx("path",{className:"react-flow__minimap-mask",d:`M${G-q},${D-q}h${L+q*2}v${W+q*2}h${-L-q*2}z + M${O.x},${O.y}h${O.width}v${O.height}h${-O.width}z`,fill:d,fillRule:"evenodd",stroke:p,strokeWidth:h,pointerEvents:"none"})]})})}P3.displayName="MiniMap";var ST=f.memo(P3),Cs;(function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"})(Cs||(Cs={}));function CT({color:e,dimensions:t,lineWidth:n}){return i.jsx("path",{stroke:e,strokeWidth:n,d:`M${t[0]/2} 0 V${t[1]} M0 ${t[1]/2} H${t[0]}`})}function kT({color:e,radius:t}){return i.jsx("circle",{cx:t,cy:t,r:t,fill:e})}const _T={[Cs.Dots]:"#91919a",[Cs.Lines]:"#eee",[Cs.Cross]:"#e2e2e2"},PT={[Cs.Dots]:1,[Cs.Lines]:1,[Cs.Cross]:6},jT=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function j3({id:e,variant:t=Cs.Dots,gap:n=20,size:r,lineWidth:o=1,offset:s=2,color:a,style:c,className:d}){const p=f.useRef(null),{transform:h,patternId:m}=Ip(jT,M1),v=a||_T[t],b=r||PT[t],w=t===Cs.Dots,y=t===Cs.Cross,S=Array.isArray(n)?n:[n,n],k=[S[0]*h[2]||1,S[1]*h[2]||1],_=b*h[2],I=y?[_,_]:k,P=w?[_/s,_/s]:[I[0]/s,I[1]/s];return i.jsxs("svg",{className:Qh(["react-flow__background",d]),style:{...c,position:"absolute",width:"100%",height:"100%",top:0,left:0},ref:p,"data-testid":"rf__background",children:[i.jsx("pattern",{id:m+e,x:h[0]%k[0],y:h[1]%k[1],width:k[0],height:k[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${P[0]},-${P[1]})`,children:w?i.jsx(kT,{color:v,radius:_/s}):i.jsx(CT,{dimensions:I,color:v,lineWidth:o})}),i.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${m+e})`})]})}j3.displayName="Background";var IT=f.memo(j3),Du;(function(e){e.Line="line",e.Handle="handle"})(Du||(Du={}));function ET({width:e,prevWidth:t,height:n,prevHeight:r,invertX:o,invertY:s}){const a=e-t,c=n-r,d=[a>0?1:a<0?-1:0,c>0?1:c<0?-1:0];return a&&o&&(d[0]=d[0]*-1),c&&s&&(d[1]=d[1]*-1),d}const I3={width:0,height:0,x:0,y:0},OT={...I3,pointerX:0,pointerY:0,aspectRatio:1};function RT({nodeId:e,position:t,variant:n=Du.Handle,className:r,style:o={},children:s,color:a,minWidth:c=10,minHeight:d=10,maxWidth:p=Number.MAX_VALUE,maxHeight:h=Number.MAX_VALUE,keepAspectRatio:m=!1,shouldResize:v,onResizeStart:b,onResize:w,onResizeEnd:y}){const S=vR(),k=typeof e=="string"?e:S,_=w_(),I=f.useRef(null),P=f.useRef(OT),E=f.useRef(I3),O=bR(),R=n===Du.Line?"right":"bottom-right",M=t??R;f.useEffect(()=>{if(!I.current||!k)return;const Q=S_(I.current),B=M.includes("right")||M.includes("left"),V=M.includes("bottom")||M.includes("top"),q=M.includes("left"),G=M.includes("top"),D=yR().on("start",L=>{const W=_.getState().nodeInternals.get(k),{xSnapped:Y,ySnapped:ae}=O(L);E.current={width:(W==null?void 0:W.width)??0,height:(W==null?void 0:W.height)??0,x:(W==null?void 0:W.position.x)??0,y:(W==null?void 0:W.position.y)??0},P.current={...E.current,pointerX:Y,pointerY:ae,aspectRatio:E.current.width/E.current.height},b==null||b(L,{...E.current})}).on("drag",L=>{const{nodeInternals:W,triggerNodeChanges:Y}=_.getState(),{xSnapped:ae,ySnapped:ye}=O(L),ue=W.get(k);if(ue){const X=[],{pointerX:K,pointerY:U,width:se,height:re,x:oe,y:pe,aspectRatio:le}=P.current,{x:ge,y:_e,width:ie,height:Se}=E.current,Fe=Math.floor(B?ae-K:0),Ae=Math.floor(V?ye-U:0);let He=P2(se+(q?-Fe:Fe),c,p),Ct=P2(re+(G?-Ae:Ae),d,h);if(m){const Re=He/Ct,Pt=B&&V,At=B&&!V,xe=V&&!B;He=Re<=le&&Pt||xe?Ct*le:He,Ct=Re>le&&Pt||At?He/le:Ct,He>=p?(He=p,Ct=p/le):He<=c&&(He=c,Ct=c/le),Ct>=h?(Ct=h,He=h*le):Ct<=d&&(Ct=d,He=d*le)}const ct=He!==ie,on=Ct!==Se;if(q||G){const Re=q?oe-(He-se):oe,Pt=G?pe-(Ct-re):pe,At=Re!==ge&&ct,xe=Pt!==_e&&on;if(At||xe){const ht={id:ue.id,type:"position",position:{x:At?Re:ge,y:xe?Pt:_e}};X.push(ht),E.current.x=ht.position.x,E.current.y=ht.position.y}}if(ct||on){const Re={id:k,type:"dimensions",updateStyle:!0,resizing:!0,dimensions:{width:He,height:Ct}};X.push(Re),E.current.width=He,E.current.height=Ct}if(X.length===0)return;const vt=ET({width:E.current.width,prevWidth:ie,height:E.current.height,prevHeight:Se,invertX:q,invertY:G}),bt={...E.current,direction:vt};if((v==null?void 0:v(L,bt))===!1)return;w==null||w(L,bt),Y(X)}}).on("end",L=>{const W={id:k,type:"dimensions",resizing:!1};y==null||y(L,{...E.current}),_.getState().triggerNodeChanges([W])});return Q.call(D),()=>{Q.on(".drag",null)}},[k,M,c,d,p,h,m,O,b,w,y]);const T=M.split("-"),A=n===Du.Line?"borderColor":"backgroundColor",$=a?{...o,[A]:a}:o;return i.jsx("div",{className:Qh(["react-flow__resize-control","nodrag",...T,n,r]),ref:I,style:$,children:s})}var MT=f.memo(RT);const E3=1/60*1e3,DT=typeof performance<"u"?()=>performance.now():()=>Date.now(),O3=typeof window<"u"?e=>window.requestAnimationFrame(e):e=>setTimeout(()=>e(DT()),E3);function TT(e){let t=[],n=[],r=0,o=!1,s=!1;const a=new WeakSet,c={schedule:(d,p=!1,h=!1)=>{const m=h&&o,v=m?t:n;return p&&a.add(d),v.indexOf(d)===-1&&(v.push(d),m&&o&&(r=t.length)),d},cancel:d=>{const p=n.indexOf(d);p!==-1&&n.splice(p,1),a.delete(d)},process:d=>{if(o){s=!0;return}if(o=!0,[t,n]=[n,t],n.length=0,r=t.length,r)for(let p=0;p(e[t]=TT(()=>Uu=!0),e),{}),NT=hd.reduce((e,t)=>{const n=rm[t];return e[t]=(r,o=!1,s=!1)=>(Uu||LT(),n.schedule(r,o,s)),e},{}),$T=hd.reduce((e,t)=>(e[t]=rm[t].cancel,e),{});hd.reduce((e,t)=>(e[t]=()=>rm[t].process(nc),e),{});const zT=e=>rm[e].process(nc),R3=e=>{Uu=!1,nc.delta=yv?E3:Math.max(Math.min(e-nc.timestamp,AT),1),nc.timestamp=e,xv=!0,hd.forEach(zT),xv=!1,Uu&&(yv=!1,O3(R3))},LT=()=>{Uu=!0,yv=!0,xv||O3(R3)},bw=()=>nc;function Y1(e){const t=Object.assign({},e);for(let n in t)t[n]===void 0&&delete t[n];return t}function md(e){const{viewBox:t="0 0 24 24",d:n,displayName:r,defaultProps:o={}}=e,s=f.Children.toArray(e.path),a=Te((c,d)=>i.jsx(Kr,{ref:d,viewBox:t,...o,...c,children:s.length?s:i.jsx("path",{fill:"currentColor",d:n})}));return a.displayName=r,a}function BT(e){const{theme:t}=xR(),n=TD();return f.useMemo(()=>AD(t.direction,{...n,...e}),[e,t.direction,n])}var FT=Object.defineProperty,HT=(e,t,n)=>t in e?FT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,gr=(e,t,n)=>(HT(e,typeof t!="symbol"?t+"":t,n),n);function yw(e){return e.sort((t,n)=>{const r=t.compareDocumentPosition(n);if(r&Node.DOCUMENT_POSITION_FOLLOWING||r&Node.DOCUMENT_POSITION_CONTAINED_BY)return-1;if(r&Node.DOCUMENT_POSITION_PRECEDING||r&Node.DOCUMENT_POSITION_CONTAINS)return 1;if(r&Node.DOCUMENT_POSITION_DISCONNECTED||r&Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC)throw Error("Cannot sort the given nodes.");return 0})}var WT=e=>typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.ELEMENT_NODE;function xw(e,t,n){let r=e+1;return n&&r>=t&&(r=0),r}function ww(e,t,n){let r=e-1;return n&&r<0&&(r=t),r}var wv=typeof window<"u"?f.useLayoutEffect:f.useEffect,zp=e=>e,VT=class{constructor(){gr(this,"descendants",new Map),gr(this,"register",e=>{if(e!=null)return WT(e)?this.registerNode(e):t=>{this.registerNode(t,e)}}),gr(this,"unregister",e=>{this.descendants.delete(e);const t=yw(Array.from(this.descendants.keys()));this.assignIndex(t)}),gr(this,"destroy",()=>{this.descendants.clear()}),gr(this,"assignIndex",e=>{this.descendants.forEach(t=>{const n=e.indexOf(t.node);t.index=n,t.node.dataset.index=t.index.toString()})}),gr(this,"count",()=>this.descendants.size),gr(this,"enabledCount",()=>this.enabledValues().length),gr(this,"values",()=>Array.from(this.descendants.values()).sort((t,n)=>t.index-n.index)),gr(this,"enabledValues",()=>this.values().filter(e=>!e.disabled)),gr(this,"item",e=>{if(this.count()!==0)return this.values()[e]}),gr(this,"enabledItem",e=>{if(this.enabledCount()!==0)return this.enabledValues()[e]}),gr(this,"first",()=>this.item(0)),gr(this,"firstEnabled",()=>this.enabledItem(0)),gr(this,"last",()=>this.item(this.descendants.size-1)),gr(this,"lastEnabled",()=>{const e=this.enabledValues().length-1;return this.enabledItem(e)}),gr(this,"indexOf",e=>{var t,n;return e&&(n=(t=this.descendants.get(e))==null?void 0:t.index)!=null?n:-1}),gr(this,"enabledIndexOf",e=>e==null?-1:this.enabledValues().findIndex(t=>t.node.isSameNode(e))),gr(this,"next",(e,t=!0)=>{const n=xw(e,this.count(),t);return this.item(n)}),gr(this,"nextEnabled",(e,t=!0)=>{const n=this.item(e);if(!n)return;const r=this.enabledIndexOf(n.node),o=xw(r,this.enabledCount(),t);return this.enabledItem(o)}),gr(this,"prev",(e,t=!0)=>{const n=ww(e,this.count()-1,t);return this.item(n)}),gr(this,"prevEnabled",(e,t=!0)=>{const n=this.item(e);if(!n)return;const r=this.enabledIndexOf(n.node),o=ww(r,this.enabledCount()-1,t);return this.enabledItem(o)}),gr(this,"registerNode",(e,t)=>{if(!e||this.descendants.has(e))return;const n=Array.from(this.descendants.keys()).concat(e),r=yw(n);t!=null&&t.disabled&&(t.disabled=!!t.disabled);const o={node:e,index:-1,...t};this.descendants.set(e,o),this.assignIndex(r)})}};function UT(e,t){if(e!=null){if(typeof e=="function"){e(t);return}try{e.current=t}catch{throw new Error(`Cannot assign value '${t}' to ref '${e}'`)}}}function cn(...e){return t=>{e.forEach(n=>{UT(n,t)})}}function GT(...e){return f.useMemo(()=>cn(...e),e)}function qT(){const e=f.useRef(new VT);return wv(()=>()=>e.current.destroy()),e.current}var[KT,M3]=Rn({name:"DescendantsProvider",errorMessage:"useDescendantsContext must be used within DescendantsProvider"});function YT(e){const t=M3(),[n,r]=f.useState(-1),o=f.useRef(null);wv(()=>()=>{o.current&&t.unregister(o.current)},[]),wv(()=>{if(!o.current)return;const a=Number(o.current.dataset.index);n!=a&&!Number.isNaN(a)&&r(a)});const s=zp(e?t.register(e):t.register);return{descendants:t,index:n,enabledIndex:t.enabledIndexOf(o.current),register:cn(s,o)}}function X1(){return[zp(KT),()=>zp(M3()),()=>qT(),o=>YT(o)]}var[XT,om]=Rn({name:"AccordionStylesContext",hookName:"useAccordionStyles",providerName:""}),[QT,Q1]=Rn({name:"AccordionItemContext",hookName:"useAccordionItemContext",providerName:""}),[JT,pde,ZT,eA]=X1(),Su=Te(function(t,n){const{getButtonProps:r}=Q1(),o=r(t,n),a={display:"flex",alignItems:"center",width:"100%",outline:0,...om().button};return i.jsx(Ie.button,{...o,className:kt("chakra-accordion__button",t.className),__css:a})});Su.displayName="AccordionButton";function Ac(e){const{value:t,defaultValue:n,onChange:r,shouldUpdate:o=(v,b)=>v!==b}=e,s=rr(r),a=rr(o),[c,d]=f.useState(n),p=t!==void 0,h=p?t:c,m=rr(v=>{const w=typeof v=="function"?v(h):v;a(h,w)&&(p||d(w),s(w))},[p,s,h,a]);return[h,m]}function tA(e){const{onChange:t,defaultIndex:n,index:r,allowMultiple:o,allowToggle:s,...a}=e;oA(e),sA(e);const c=ZT(),[d,p]=f.useState(-1);f.useEffect(()=>()=>{p(-1)},[]);const[h,m]=Ac({value:r,defaultValue(){return o?n??[]:n??-1},onChange:t});return{index:h,setIndex:m,htmlProps:a,getAccordionItemProps:b=>{let w=!1;return b!==null&&(w=Array.isArray(h)?h.includes(b):h===b),{isOpen:w,onChange:S=>{if(b!==null)if(o&&Array.isArray(h)){const k=S?h.concat(b):h.filter(_=>_!==b);m(k)}else S?m(b):s&&m(-1)}}},focusedIndex:d,setFocusedIndex:p,descendants:c}}var[nA,J1]=Rn({name:"AccordionContext",hookName:"useAccordionContext",providerName:"Accordion"});function rA(e){const{isDisabled:t,isFocusable:n,id:r,...o}=e,{getAccordionItemProps:s,setFocusedIndex:a}=J1(),c=f.useRef(null),d=f.useId(),p=r??d,h=`accordion-button-${p}`,m=`accordion-panel-${p}`;aA(e);const{register:v,index:b,descendants:w}=eA({disabled:t&&!n}),{isOpen:y,onChange:S}=s(b===-1?null:b);iA({isOpen:y,isDisabled:t});const k=()=>{S==null||S(!0)},_=()=>{S==null||S(!1)},I=f.useCallback(()=>{S==null||S(!y),a(b)},[b,a,y,S]),P=f.useCallback(M=>{const A={ArrowDown:()=>{const $=w.nextEnabled(b);$==null||$.node.focus()},ArrowUp:()=>{const $=w.prevEnabled(b);$==null||$.node.focus()},Home:()=>{const $=w.firstEnabled();$==null||$.node.focus()},End:()=>{const $=w.lastEnabled();$==null||$.node.focus()}}[M.key];A&&(M.preventDefault(),A(M))},[w,b]),E=f.useCallback(()=>{a(b)},[a,b]),O=f.useCallback(function(T={},A=null){return{...T,type:"button",ref:cn(v,c,A),id:h,disabled:!!t,"aria-expanded":!!y,"aria-controls":m,onClick:et(T.onClick,I),onFocus:et(T.onFocus,E),onKeyDown:et(T.onKeyDown,P)}},[h,t,y,I,E,P,m,v]),R=f.useCallback(function(T={},A=null){return{...T,ref:A,role:"region",id:m,"aria-labelledby":h,hidden:!y}},[h,y,m]);return{isOpen:y,isDisabled:t,isFocusable:n,onOpen:k,onClose:_,getButtonProps:O,getPanelProps:R,htmlProps:o}}function oA(e){const t=e.index||e.defaultIndex,n=t!=null&&!Array.isArray(t)&&e.allowMultiple;ld({condition:!!n,message:`If 'allowMultiple' is passed, then 'index' or 'defaultIndex' must be an array. You passed: ${typeof t},`})}function sA(e){ld({condition:!!(e.allowMultiple&&e.allowToggle),message:"If 'allowMultiple' is passed, 'allowToggle' will be ignored. Either remove 'allowToggle' or 'allowMultiple' depending on whether you want multiple accordions visible or not"})}function aA(e){ld({condition:!!(e.isFocusable&&!e.isDisabled),message:`Using only 'isFocusable', this prop is reserved for situations where you pass 'isDisabled' but you still want the element to receive focus (A11y). Either remove it or pass 'isDisabled' as well. + `})}function iA(e){ld({condition:e.isOpen&&!!e.isDisabled,message:"Cannot open a disabled accordion item"})}function Cu(e){const{isOpen:t,isDisabled:n}=Q1(),{reduceMotion:r}=J1(),o=kt("chakra-accordion__icon",e.className),s=om(),a={opacity:n?.4:1,transform:t?"rotate(-180deg)":void 0,transition:r?void 0:"transform 0.2s",transformOrigin:"center",...s.icon};return i.jsx(Kr,{viewBox:"0 0 24 24","aria-hidden":!0,className:o,__css:a,...e,children:i.jsx("path",{fill:"currentColor",d:"M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"})})}Cu.displayName="AccordionIcon";var ku=Te(function(t,n){const{children:r,className:o}=t,{htmlProps:s,...a}=rA(t),d={...om().container,overflowAnchor:"none"},p=f.useMemo(()=>a,[a]);return i.jsx(QT,{value:p,children:i.jsx(Ie.div,{ref:n,...s,className:kt("chakra-accordion__item",o),__css:d,children:typeof r=="function"?r({isExpanded:!!a.isOpen,isDisabled:!!a.isDisabled}):r})})});ku.displayName="AccordionItem";var Gi={ease:[.25,.1,.25,1],easeIn:[.4,0,1,1],easeOut:[0,0,.2,1],easeInOut:[.4,0,.2,1]},uu={scale:{enter:{scale:1},exit:{scale:.95}},fade:{enter:{opacity:1},exit:{opacity:0}},pushLeft:{enter:{x:"100%"},exit:{x:"-30%"}},pushRight:{enter:{x:"-100%"},exit:{x:"30%"}},pushUp:{enter:{y:"100%"},exit:{y:"-30%"}},pushDown:{enter:{y:"-100%"},exit:{y:"30%"}},slideLeft:{position:{left:0,top:0,bottom:0,width:"100%"},enter:{x:0,y:0},exit:{x:"-100%",y:0}},slideRight:{position:{right:0,top:0,bottom:0,width:"100%"},enter:{x:0,y:0},exit:{x:"100%",y:0}},slideUp:{position:{top:0,left:0,right:0,maxWidth:"100vw"},enter:{x:0,y:0},exit:{x:0,y:"-100%"}},slideDown:{position:{bottom:0,left:0,right:0,maxWidth:"100vw"},enter:{x:0,y:0},exit:{x:0,y:"100%"}}};function Sv(e){var t;switch((t=e==null?void 0:e.direction)!=null?t:"right"){case"right":return uu.slideRight;case"left":return uu.slideLeft;case"bottom":return uu.slideDown;case"top":return uu.slideUp;default:return uu.slideRight}}var Ki={enter:{duration:.2,ease:Gi.easeOut},exit:{duration:.1,ease:Gi.easeIn}},ks={enter:(e,t)=>({...e,delay:typeof t=="number"?t:t==null?void 0:t.enter}),exit:(e,t)=>({...e,delay:typeof t=="number"?t:t==null?void 0:t.exit})},lA=e=>e!=null&&parseInt(e.toString(),10)>0,Sw={exit:{height:{duration:.2,ease:Gi.ease},opacity:{duration:.3,ease:Gi.ease}},enter:{height:{duration:.3,ease:Gi.ease},opacity:{duration:.4,ease:Gi.ease}}},cA={exit:({animateOpacity:e,startingHeight:t,transition:n,transitionEnd:r,delay:o})=>{var s;return{...e&&{opacity:lA(t)?1:0},height:t,transitionEnd:r==null?void 0:r.exit,transition:(s=n==null?void 0:n.exit)!=null?s:ks.exit(Sw.exit,o)}},enter:({animateOpacity:e,endingHeight:t,transition:n,transitionEnd:r,delay:o})=>{var s;return{...e&&{opacity:1},height:t,transitionEnd:r==null?void 0:r.enter,transition:(s=n==null?void 0:n.enter)!=null?s:ks.enter(Sw.enter,o)}}},sm=f.forwardRef((e,t)=>{const{in:n,unmountOnExit:r,animateOpacity:o=!0,startingHeight:s=0,endingHeight:a="auto",style:c,className:d,transition:p,transitionEnd:h,...m}=e,[v,b]=f.useState(!1);f.useEffect(()=>{const _=setTimeout(()=>{b(!0)});return()=>clearTimeout(_)},[]),ld({condition:Number(s)>0&&!!r,message:"startingHeight and unmountOnExit are mutually exclusive. You can't use them together"});const w=parseFloat(s.toString())>0,y={startingHeight:s,endingHeight:a,animateOpacity:o,transition:v?p:{enter:{duration:0}},transitionEnd:{enter:h==null?void 0:h.enter,exit:r?h==null?void 0:h.exit:{...h==null?void 0:h.exit,display:w?"block":"none"}}},S=r?n:!0,k=n||r?"enter":"exit";return i.jsx(Fo,{initial:!1,custom:y,children:S&&i.jsx(Xr.div,{ref:t,...m,className:kt("chakra-collapse",d),style:{overflow:"hidden",display:"block",...c},custom:y,variants:cA,initial:r?"exit":!1,animate:k,exit:"exit"})})});sm.displayName="Collapse";var uA={enter:({transition:e,transitionEnd:t,delay:n}={})=>{var r;return{opacity:1,transition:(r=e==null?void 0:e.enter)!=null?r:ks.enter(Ki.enter,n),transitionEnd:t==null?void 0:t.enter}},exit:({transition:e,transitionEnd:t,delay:n}={})=>{var r;return{opacity:0,transition:(r=e==null?void 0:e.exit)!=null?r:ks.exit(Ki.exit,n),transitionEnd:t==null?void 0:t.exit}}},D3={initial:"exit",animate:"enter",exit:"exit",variants:uA},dA=f.forwardRef(function(t,n){const{unmountOnExit:r,in:o,className:s,transition:a,transitionEnd:c,delay:d,...p}=t,h=o||r?"enter":"exit",m=r?o&&r:!0,v={transition:a,transitionEnd:c,delay:d};return i.jsx(Fo,{custom:v,children:m&&i.jsx(Xr.div,{ref:n,className:kt("chakra-fade",s),custom:v,...D3,animate:h,...p})})});dA.displayName="Fade";var fA={exit:({reverse:e,initialScale:t,transition:n,transitionEnd:r,delay:o})=>{var s;return{opacity:0,...e?{scale:t,transitionEnd:r==null?void 0:r.exit}:{transitionEnd:{scale:t,...r==null?void 0:r.exit}},transition:(s=n==null?void 0:n.exit)!=null?s:ks.exit(Ki.exit,o)}},enter:({transitionEnd:e,transition:t,delay:n})=>{var r;return{opacity:1,scale:1,transition:(r=t==null?void 0:t.enter)!=null?r:ks.enter(Ki.enter,n),transitionEnd:e==null?void 0:e.enter}}},T3={initial:"exit",animate:"enter",exit:"exit",variants:fA},pA=f.forwardRef(function(t,n){const{unmountOnExit:r,in:o,reverse:s=!0,initialScale:a=.95,className:c,transition:d,transitionEnd:p,delay:h,...m}=t,v=r?o&&r:!0,b=o||r?"enter":"exit",w={initialScale:a,reverse:s,transition:d,transitionEnd:p,delay:h};return i.jsx(Fo,{custom:w,children:v&&i.jsx(Xr.div,{ref:n,className:kt("chakra-offset-slide",c),...T3,animate:b,custom:w,...m})})});pA.displayName="ScaleFade";var hA={initial:({offsetX:e,offsetY:t,transition:n,transitionEnd:r,delay:o})=>{var s;return{opacity:0,x:e,y:t,transition:(s=n==null?void 0:n.exit)!=null?s:ks.exit(Ki.exit,o),transitionEnd:r==null?void 0:r.exit}},enter:({transition:e,transitionEnd:t,delay:n})=>{var r;return{opacity:1,x:0,y:0,transition:(r=e==null?void 0:e.enter)!=null?r:ks.enter(Ki.enter,n),transitionEnd:t==null?void 0:t.enter}},exit:({offsetY:e,offsetX:t,transition:n,transitionEnd:r,reverse:o,delay:s})=>{var a;const c={x:t,y:e};return{opacity:0,transition:(a=n==null?void 0:n.exit)!=null?a:ks.exit(Ki.exit,s),...o?{...c,transitionEnd:r==null?void 0:r.exit}:{transitionEnd:{...c,...r==null?void 0:r.exit}}}}},Cv={initial:"initial",animate:"enter",exit:"exit",variants:hA},mA=f.forwardRef(function(t,n){const{unmountOnExit:r,in:o,reverse:s=!0,className:a,offsetX:c=0,offsetY:d=8,transition:p,transitionEnd:h,delay:m,...v}=t,b=r?o&&r:!0,w=o||r?"enter":"exit",y={offsetX:c,offsetY:d,reverse:s,transition:p,transitionEnd:h,delay:m};return i.jsx(Fo,{custom:y,children:b&&i.jsx(Xr.div,{ref:n,className:kt("chakra-offset-slide",a),custom:y,...Cv,animate:w,...v})})});mA.displayName="SlideFade";var Cw={exit:{duration:.15,ease:Gi.easeInOut},enter:{type:"spring",damping:25,stiffness:180}},gA={exit:({direction:e,transition:t,transitionEnd:n,delay:r})=>{var o;const{exit:s}=Sv({direction:e});return{...s,transition:(o=t==null?void 0:t.exit)!=null?o:ks.exit(Cw.exit,r),transitionEnd:n==null?void 0:n.exit}},enter:({direction:e,transitionEnd:t,transition:n,delay:r})=>{var o;const{enter:s}=Sv({direction:e});return{...s,transition:(o=n==null?void 0:n.enter)!=null?o:ks.enter(Cw.enter,r),transitionEnd:t==null?void 0:t.enter}}},A3=f.forwardRef(function(t,n){const{direction:r="right",style:o,unmountOnExit:s,in:a,className:c,transition:d,transitionEnd:p,delay:h,motionProps:m,...v}=t,b=Sv({direction:r}),w=Object.assign({position:"fixed"},b.position,o),y=s?a&&s:!0,S=a||s?"enter":"exit",k={transitionEnd:p,transition:d,direction:r,delay:h};return i.jsx(Fo,{custom:k,children:y&&i.jsx(Xr.div,{...v,ref:n,initial:"exit",className:kt("chakra-slide",c),animate:S,exit:"exit",custom:k,variants:gA,style:w,...m})})});A3.displayName="Slide";var _u=Te(function(t,n){const{className:r,motionProps:o,...s}=t,{reduceMotion:a}=J1(),{getPanelProps:c,isOpen:d}=Q1(),p=c(s,n),h=kt("chakra-accordion__panel",r),m=om();a||delete p.hidden;const v=i.jsx(Ie.div,{...p,__css:m.panel,className:h});return a?v:i.jsx(sm,{in:d,...o,children:v})});_u.displayName="AccordionPanel";var N3=Te(function({children:t,reduceMotion:n,...r},o){const s=Br("Accordion",r),a=qn(r),{htmlProps:c,descendants:d,...p}=tA(a),h=f.useMemo(()=>({...p,reduceMotion:!!n}),[p,n]);return i.jsx(JT,{value:d,children:i.jsx(nA,{value:h,children:i.jsx(XT,{value:s,children:i.jsx(Ie.div,{ref:o,...c,className:kt("chakra-accordion",r.className),__css:s.root,children:t})})})})});N3.displayName="Accordion";function gd(e){return f.Children.toArray(e).filter(t=>f.isValidElement(t))}var[vA,bA]=Rn({strict:!1,name:"ButtonGroupContext"}),yA={horizontal:{"> *:first-of-type:not(:last-of-type)":{borderEndRadius:0},"> *:not(:first-of-type):not(:last-of-type)":{borderRadius:0},"> *:not(:first-of-type):last-of-type":{borderStartRadius:0}},vertical:{"> *:first-of-type:not(:last-of-type)":{borderBottomRadius:0},"> *:not(:first-of-type):not(:last-of-type)":{borderRadius:0},"> *:not(:first-of-type):last-of-type":{borderTopRadius:0}}},xA={horizontal:e=>({"& > *:not(style) ~ *:not(style)":{marginStart:e}}),vertical:e=>({"& > *:not(style) ~ *:not(style)":{marginTop:e}})},nr=Te(function(t,n){const{size:r,colorScheme:o,variant:s,className:a,spacing:c="0.5rem",isAttached:d,isDisabled:p,orientation:h="horizontal",...m}=t,v=kt("chakra-button__group",a),b=f.useMemo(()=>({size:r,colorScheme:o,variant:s,isDisabled:p}),[r,o,s,p]);let w={display:"inline-flex",...d?yA[h]:xA[h](c)};const y=h==="vertical";return i.jsx(vA,{value:b,children:i.jsx(Ie.div,{ref:n,role:"group",__css:w,className:v,"data-attached":d?"":void 0,"data-orientation":h,flexDir:y?"column":void 0,...m})})});nr.displayName="ButtonGroup";function wA(e){const[t,n]=f.useState(!e);return{ref:f.useCallback(s=>{s&&n(s.tagName==="BUTTON")},[]),type:t?"button":void 0}}function kv(e){const{children:t,className:n,...r}=e,o=f.isValidElement(t)?f.cloneElement(t,{"aria-hidden":!0,focusable:!1}):t,s=kt("chakra-button__icon",n);return i.jsx(Ie.span,{display:"inline-flex",alignSelf:"center",flexShrink:0,...r,className:s,children:o})}kv.displayName="ButtonIcon";function Lp(e){const{label:t,placement:n,spacing:r="0.5rem",children:o=i.jsx(dl,{color:"currentColor",width:"1em",height:"1em"}),className:s,__css:a,...c}=e,d=kt("chakra-button__spinner",s),p=n==="start"?"marginEnd":"marginStart",h=f.useMemo(()=>({display:"flex",alignItems:"center",position:t?"relative":"absolute",[p]:t?r:0,fontSize:"1em",lineHeight:"normal",...a}),[a,t,p,r]);return i.jsx(Ie.div,{className:d,...c,__css:h,children:o})}Lp.displayName="ButtonSpinner";var gc=Te((e,t)=>{const n=bA(),r=$a("Button",{...n,...e}),{isDisabled:o=n==null?void 0:n.isDisabled,isLoading:s,isActive:a,children:c,leftIcon:d,rightIcon:p,loadingText:h,iconSpacing:m="0.5rem",type:v,spinner:b,spinnerPlacement:w="start",className:y,as:S,...k}=qn(e),_=f.useMemo(()=>{const O={...r==null?void 0:r._focus,zIndex:1};return{display:"inline-flex",appearance:"none",alignItems:"center",justifyContent:"center",userSelect:"none",position:"relative",whiteSpace:"nowrap",verticalAlign:"middle",outline:"none",...r,...!!n&&{_focus:O}}},[r,n]),{ref:I,type:P}=wA(S),E={rightIcon:p,leftIcon:d,iconSpacing:m,children:c};return i.jsxs(Ie.button,{ref:GT(t,I),as:S,type:v??P,"data-active":tn(a),"data-loading":tn(s),__css:_,className:kt("chakra-button",y),...k,disabled:o||s,children:[s&&w==="start"&&i.jsx(Lp,{className:"chakra-button__spinner--start",label:h,placement:"start",spacing:m,children:b}),s?h||i.jsx(Ie.span,{opacity:0,children:i.jsx(kw,{...E})}):i.jsx(kw,{...E}),s&&w==="end"&&i.jsx(Lp,{className:"chakra-button__spinner--end",label:h,placement:"end",spacing:m,children:b})]})});gc.displayName="Button";function kw(e){const{leftIcon:t,rightIcon:n,children:r,iconSpacing:o}=e;return i.jsxs(i.Fragment,{children:[t&&i.jsx(kv,{marginEnd:o,children:t}),r,n&&i.jsx(kv,{marginStart:o,children:n})]})}var Sa=Te((e,t)=>{const{icon:n,children:r,isRound:o,"aria-label":s,...a}=e,c=n||r,d=f.isValidElement(c)?f.cloneElement(c,{"aria-hidden":!0,focusable:!1}):null;return i.jsx(gc,{padding:"0",borderRadius:o?"full":void 0,ref:t,"aria-label":s,...a,children:d})});Sa.displayName="IconButton";var[hde,SA]=Rn({name:"CheckboxGroupContext",strict:!1});function CA(e){const[t,n]=f.useState(e),[r,o]=f.useState(!1);return e!==t&&(o(!0),n(e)),r}function kA(e){return i.jsx(Ie.svg,{width:"1.2em",viewBox:"0 0 12 10",style:{fill:"none",strokeWidth:2,stroke:"currentColor",strokeDasharray:16},...e,children:i.jsx("polyline",{points:"1.5 6 4.5 9 10.5 1"})})}function _A(e){return i.jsx(Ie.svg,{width:"1.2em",viewBox:"0 0 24 24",style:{stroke:"currentColor",strokeWidth:4},...e,children:i.jsx("line",{x1:"21",x2:"3",y1:"12",y2:"12"})})}function PA(e){const{isIndeterminate:t,isChecked:n,...r}=e,o=t?_A:kA;return n||t?i.jsx(Ie.div,{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:i.jsx(o,{...r})}):null}var[jA,$3]=Rn({name:"FormControlStylesContext",errorMessage:`useFormControlStyles returned is 'undefined'. Seems you forgot to wrap the components in "" `}),[IA,vd]=Rn({strict:!1,name:"FormControlContext"});function EA(e){const{id:t,isRequired:n,isInvalid:r,isDisabled:o,isReadOnly:s,...a}=e,c=f.useId(),d=t||`field-${c}`,p=`${d}-label`,h=`${d}-feedback`,m=`${d}-helptext`,[v,b]=f.useState(!1),[w,y]=f.useState(!1),[S,k]=f.useState(!1),_=f.useCallback((R={},M=null)=>({id:m,...R,ref:cn(M,T=>{T&&y(!0)})}),[m]),I=f.useCallback((R={},M=null)=>({...R,ref:M,"data-focus":tn(S),"data-disabled":tn(o),"data-invalid":tn(r),"data-readonly":tn(s),id:R.id!==void 0?R.id:p,htmlFor:R.htmlFor!==void 0?R.htmlFor:d}),[d,o,S,r,s,p]),P=f.useCallback((R={},M=null)=>({id:h,...R,ref:cn(M,T=>{T&&b(!0)}),"aria-live":"polite"}),[h]),E=f.useCallback((R={},M=null)=>({...R,...a,ref:M,role:"group"}),[a]),O=f.useCallback((R={},M=null)=>({...R,ref:M,role:"presentation","aria-hidden":!0,children:R.children||"*"}),[]);return{isRequired:!!n,isInvalid:!!r,isReadOnly:!!s,isDisabled:!!o,isFocused:!!S,onFocus:()=>k(!0),onBlur:()=>k(!1),hasFeedbackText:v,setHasFeedbackText:b,hasHelpText:w,setHasHelpText:y,id:d,labelId:p,feedbackId:h,helpTextId:m,htmlProps:a,getHelpTextProps:_,getErrorMessageProps:P,getRootProps:E,getLabelProps:I,getRequiredIndicatorProps:O}}var ho=Te(function(t,n){const r=Br("Form",t),o=qn(t),{getRootProps:s,htmlProps:a,...c}=EA(o),d=kt("chakra-form-control",t.className);return i.jsx(IA,{value:c,children:i.jsx(jA,{value:r,children:i.jsx(Ie.div,{...s({},n),className:d,__css:r.container})})})});ho.displayName="FormControl";var OA=Te(function(t,n){const r=vd(),o=$3(),s=kt("chakra-form__helper-text",t.className);return i.jsx(Ie.div,{...r==null?void 0:r.getHelpTextProps(t,n),__css:o.helperText,className:s})});OA.displayName="FormHelperText";var zo=Te(function(t,n){var r;const o=$a("FormLabel",t),s=qn(t),{className:a,children:c,requiredIndicator:d=i.jsx(z3,{}),optionalIndicator:p=null,...h}=s,m=vd(),v=(r=m==null?void 0:m.getLabelProps(h,n))!=null?r:{ref:n,...h};return i.jsxs(Ie.label,{...v,className:kt("chakra-form__label",s.className),__css:{display:"block",textAlign:"start",...o},children:[c,m!=null&&m.isRequired?d:p]})});zo.displayName="FormLabel";var z3=Te(function(t,n){const r=vd(),o=$3();if(!(r!=null&&r.isRequired))return null;const s=kt("chakra-form__required-indicator",t.className);return i.jsx(Ie.span,{...r==null?void 0:r.getRequiredIndicatorProps(t,n),__css:o.requiredIndicator,className:s})});z3.displayName="RequiredIndicator";function Z1(e){const{isDisabled:t,isInvalid:n,isReadOnly:r,isRequired:o,...s}=eb(e);return{...s,disabled:t,readOnly:r,required:o,"aria-invalid":ns(n),"aria-required":ns(o),"aria-readonly":ns(r)}}function eb(e){var t,n,r;const o=vd(),{id:s,disabled:a,readOnly:c,required:d,isRequired:p,isInvalid:h,isReadOnly:m,isDisabled:v,onFocus:b,onBlur:w,...y}=e,S=e["aria-describedby"]?[e["aria-describedby"]]:[];return o!=null&&o.hasFeedbackText&&(o!=null&&o.isInvalid)&&S.push(o.feedbackId),o!=null&&o.hasHelpText&&S.push(o.helpTextId),{...y,"aria-describedby":S.join(" ")||void 0,id:s??(o==null?void 0:o.id),isDisabled:(t=a??v)!=null?t:o==null?void 0:o.isDisabled,isReadOnly:(n=c??m)!=null?n:o==null?void 0:o.isReadOnly,isRequired:(r=d??p)!=null?r:o==null?void 0:o.isRequired,isInvalid:h??(o==null?void 0:o.isInvalid),onFocus:et(o==null?void 0:o.onFocus,b),onBlur:et(o==null?void 0:o.onBlur,w)}}var tb={border:"0",clip:"rect(0, 0, 0, 0)",height:"1px",width:"1px",margin:"-1px",padding:"0",overflow:"hidden",whiteSpace:"nowrap",position:"absolute"},L3=Ie("span",{baseStyle:tb});L3.displayName="VisuallyHidden";var RA=Ie("input",{baseStyle:tb});RA.displayName="VisuallyHiddenInput";var _w=!1,bd=null,nl=!1,_v=!1,Pv=new Set;function nb(e,t){Pv.forEach(n=>n(e,t))}var MA=typeof window<"u"&&window.navigator!=null?/^Mac/.test(window.navigator.platform):!1;function DA(e){return!(e.metaKey||!MA&&e.altKey||e.ctrlKey||e.key==="Control"||e.key==="Shift"||e.key==="Meta")}function Pw(e){nl=!0,DA(e)&&(bd="keyboard",nb("keyboard",e))}function Dl(e){if(bd="pointer",e.type==="mousedown"||e.type==="pointerdown"){nl=!0;const t=e.composedPath?e.composedPath()[0]:e.target;let n=!1;try{n=t.matches(":focus-visible")}catch{}if(n)return;nb("pointer",e)}}function TA(e){return e.mozInputSource===0&&e.isTrusted?!0:e.detail===0&&!e.pointerType}function AA(e){TA(e)&&(nl=!0,bd="virtual")}function NA(e){e.target===window||e.target===document||(!nl&&!_v&&(bd="virtual",nb("virtual",e)),nl=!1,_v=!1)}function $A(){nl=!1,_v=!0}function jw(){return bd!=="pointer"}function zA(){if(typeof window>"u"||_w)return;const{focus:e}=HTMLElement.prototype;HTMLElement.prototype.focus=function(...n){nl=!0,e.apply(this,n)},document.addEventListener("keydown",Pw,!0),document.addEventListener("keyup",Pw,!0),document.addEventListener("click",AA,!0),window.addEventListener("focus",NA,!0),window.addEventListener("blur",$A,!1),typeof PointerEvent<"u"?(document.addEventListener("pointerdown",Dl,!0),document.addEventListener("pointermove",Dl,!0),document.addEventListener("pointerup",Dl,!0)):(document.addEventListener("mousedown",Dl,!0),document.addEventListener("mousemove",Dl,!0),document.addEventListener("mouseup",Dl,!0)),_w=!0}function B3(e){zA(),e(jw());const t=()=>e(jw());return Pv.add(t),()=>{Pv.delete(t)}}function LA(e,t=[]){const n=Object.assign({},e);for(const r of t)r in n&&delete n[r];return n}function F3(e={}){const t=eb(e),{isDisabled:n,isReadOnly:r,isRequired:o,isInvalid:s,id:a,onBlur:c,onFocus:d,"aria-describedby":p}=t,{defaultChecked:h,isChecked:m,isFocusable:v,onChange:b,isIndeterminate:w,name:y,value:S,tabIndex:k=void 0,"aria-label":_,"aria-labelledby":I,"aria-invalid":P,...E}=e,O=LA(E,["isDisabled","isReadOnly","isRequired","isInvalid","id","onBlur","onFocus","aria-describedby"]),R=rr(b),M=rr(c),T=rr(d),[A,$]=f.useState(!1),[Q,B]=f.useState(!1),[V,q]=f.useState(!1),[G,D]=f.useState(!1);f.useEffect(()=>B3($),[]);const L=f.useRef(null),[W,Y]=f.useState(!0),[ae,ye]=f.useState(!!h),ue=m!==void 0,X=ue?m:ae,K=f.useCallback(ie=>{if(r||n){ie.preventDefault();return}ue||ye(X?ie.target.checked:w?!0:ie.target.checked),R==null||R(ie)},[r,n,X,ue,w,R]);Zl(()=>{L.current&&(L.current.indeterminate=!!w)},[w]),Ba(()=>{n&&B(!1)},[n,B]),Zl(()=>{const ie=L.current;ie!=null&&ie.form&&(ie.form.onreset=()=>{ye(!!h)})},[]);const U=n&&!v,se=f.useCallback(ie=>{ie.key===" "&&D(!0)},[D]),re=f.useCallback(ie=>{ie.key===" "&&D(!1)},[D]);Zl(()=>{if(!L.current)return;L.current.checked!==X&&ye(L.current.checked)},[L.current]);const oe=f.useCallback((ie={},Se=null)=>{const Fe=Ae=>{Q&&Ae.preventDefault(),D(!0)};return{...ie,ref:Se,"data-active":tn(G),"data-hover":tn(V),"data-checked":tn(X),"data-focus":tn(Q),"data-focus-visible":tn(Q&&A),"data-indeterminate":tn(w),"data-disabled":tn(n),"data-invalid":tn(s),"data-readonly":tn(r),"aria-hidden":!0,onMouseDown:et(ie.onMouseDown,Fe),onMouseUp:et(ie.onMouseUp,()=>D(!1)),onMouseEnter:et(ie.onMouseEnter,()=>q(!0)),onMouseLeave:et(ie.onMouseLeave,()=>q(!1))}},[G,X,n,Q,A,V,w,s,r]),pe=f.useCallback((ie={},Se=null)=>({...O,...ie,ref:cn(Se,Fe=>{Fe&&Y(Fe.tagName==="LABEL")}),onClick:et(ie.onClick,()=>{var Fe;W||((Fe=L.current)==null||Fe.click(),requestAnimationFrame(()=>{var Ae;(Ae=L.current)==null||Ae.focus({preventScroll:!0})}))}),"data-disabled":tn(n),"data-checked":tn(X),"data-invalid":tn(s)}),[O,n,X,s,W]),le=f.useCallback((ie={},Se=null)=>({...ie,ref:cn(L,Se),type:"checkbox",name:y,value:S,id:a,tabIndex:k,onChange:et(ie.onChange,K),onBlur:et(ie.onBlur,M,()=>B(!1)),onFocus:et(ie.onFocus,T,()=>B(!0)),onKeyDown:et(ie.onKeyDown,se),onKeyUp:et(ie.onKeyUp,re),required:o,checked:X,disabled:U,readOnly:r,"aria-label":_,"aria-labelledby":I,"aria-invalid":P?!!P:s,"aria-describedby":p,"aria-disabled":n,style:tb}),[y,S,a,K,M,T,se,re,o,X,U,r,_,I,P,s,p,n,k]),ge=f.useCallback((ie={},Se=null)=>({...ie,ref:Se,onMouseDown:et(ie.onMouseDown,BA),"data-disabled":tn(n),"data-checked":tn(X),"data-invalid":tn(s)}),[X,n,s]);return{state:{isInvalid:s,isFocused:Q,isChecked:X,isActive:G,isHovered:V,isIndeterminate:w,isDisabled:n,isReadOnly:r,isRequired:o},getRootProps:pe,getCheckboxProps:oe,getInputProps:le,getLabelProps:ge,htmlProps:O}}function BA(e){e.preventDefault(),e.stopPropagation()}var FA={display:"inline-flex",alignItems:"center",justifyContent:"center",verticalAlign:"top",userSelect:"none",flexShrink:0},HA={cursor:"pointer",display:"inline-flex",alignItems:"center",verticalAlign:"top",position:"relative"},WA=za({from:{opacity:0,strokeDashoffset:16,transform:"scale(0.95)"},to:{opacity:1,strokeDashoffset:0,transform:"scale(1)"}}),VA=za({from:{opacity:0},to:{opacity:1}}),UA=za({from:{transform:"scaleX(0.65)"},to:{transform:"scaleX(1)"}}),H3=Te(function(t,n){const r=SA(),o={...r,...t},s=Br("Checkbox",o),a=qn(t),{spacing:c="0.5rem",className:d,children:p,iconColor:h,iconSize:m,icon:v=i.jsx(PA,{}),isChecked:b,isDisabled:w=r==null?void 0:r.isDisabled,onChange:y,inputProps:S,...k}=a;let _=b;r!=null&&r.value&&a.value&&(_=r.value.includes(a.value));let I=y;r!=null&&r.onChange&&a.value&&(I=Jh(r.onChange,y));const{state:P,getInputProps:E,getCheckboxProps:O,getLabelProps:R,getRootProps:M}=F3({...k,isDisabled:w,isChecked:_,onChange:I}),T=CA(P.isChecked),A=f.useMemo(()=>({animation:T?P.isIndeterminate?`${VA} 20ms linear, ${UA} 200ms linear`:`${WA} 200ms linear`:void 0,fontSize:m,color:h,...s.icon}),[h,m,T,P.isIndeterminate,s.icon]),$=f.cloneElement(v,{__css:A,isIndeterminate:P.isIndeterminate,isChecked:P.isChecked});return i.jsxs(Ie.label,{__css:{...HA,...s.container},className:kt("chakra-checkbox",d),...M(),children:[i.jsx("input",{className:"chakra-checkbox__input",...E(S,n)}),i.jsx(Ie.span,{__css:{...FA,...s.control},className:"chakra-checkbox__control",...O(),children:$}),p&&i.jsx(Ie.span,{className:"chakra-checkbox__label",...R(),__css:{marginStart:c,...s.label},children:p})]})});H3.displayName="Checkbox";function GA(e){const t=parseFloat(e);return typeof t!="number"||Number.isNaN(t)?0:t}function rb(e,t){let n=GA(e);const r=10**(t??10);return n=Math.round(n*r)/r,t?n.toFixed(t):n.toString()}function jv(e){if(!Number.isFinite(e))return 0;let t=1,n=0;for(;Math.round(e*t)/t!==e;)t*=10,n+=1;return n}function Bp(e,t,n){return(e-t)*100/(n-t)}function W3(e,t,n){return(n-t)*e+t}function Iv(e,t,n){const r=Math.round((e-t)/n)*n+t,o=jv(n);return rb(r,o)}function rc(e,t,n){return e==null?e:(n{var A;return r==null?"":(A=f0(r,s,n))!=null?A:""}),v=typeof o<"u",b=v?o:h,w=V3(ni(b),s),y=n??w,S=f.useCallback(A=>{A!==b&&(v||m(A.toString()),p==null||p(A.toString(),ni(A)))},[p,v,b]),k=f.useCallback(A=>{let $=A;return d&&($=rc($,a,c)),rb($,y)},[y,d,c,a]),_=f.useCallback((A=s)=>{let $;b===""?$=ni(A):$=ni(b)+A,$=k($),S($)},[k,s,S,b]),I=f.useCallback((A=s)=>{let $;b===""?$=ni(-A):$=ni(b)-A,$=k($),S($)},[k,s,S,b]),P=f.useCallback(()=>{var A;let $;r==null?$="":$=(A=f0(r,s,n))!=null?A:a,S($)},[r,n,s,S,a]),E=f.useCallback(A=>{var $;const Q=($=f0(A,s,y))!=null?$:a;S(Q)},[y,s,S,a]),O=ni(b);return{isOutOfRange:O>c||O" `}),[YA,G3]=Rn({name:"EditableContext",errorMessage:"useEditableContext: context is undefined. Seems you forgot to wrap the editable components in ``"}),q3={fontSize:"inherit",fontWeight:"inherit",textAlign:"inherit",bg:"transparent"},K3=Te(function(t,n){const{getInputProps:r}=G3(),o=U3(),s=r(t,n),a=kt("chakra-editable__input",t.className);return i.jsx(Ie.input,{...s,__css:{outline:0,...q3,...o.input},className:a})});K3.displayName="EditableInput";var Y3=Te(function(t,n){const{getPreviewProps:r}=G3(),o=U3(),s=r(t,n),a=kt("chakra-editable__preview",t.className);return i.jsx(Ie.span,{...s,__css:{cursor:"text",display:"inline-block",...q3,...o.preview},className:a})});Y3.displayName="EditablePreview";function Yi(e,t,n,r){const o=rr(n);return f.useEffect(()=>{const s=typeof e=="function"?e():e??document;if(!(!n||!s))return s.addEventListener(t,o,r),()=>{s.removeEventListener(t,o,r)}},[t,e,r,o,n]),()=>{const s=typeof e=="function"?e():e??document;s==null||s.removeEventListener(t,o,r)}}function XA(e){return"current"in e}var X3=()=>typeof window<"u";function QA(){var e;const t=navigator.userAgentData;return(e=t==null?void 0:t.platform)!=null?e:navigator.platform}var JA=e=>X3()&&e.test(navigator.vendor),ZA=e=>X3()&&e.test(QA()),e9=()=>ZA(/mac|iphone|ipad|ipod/i),t9=()=>e9()&&JA(/apple/i);function Q3(e){const{ref:t,elements:n,enabled:r}=e,o=()=>{var s,a;return(a=(s=t.current)==null?void 0:s.ownerDocument)!=null?a:document};Yi(o,"pointerdown",s=>{if(!t9()||!r)return;const a=s.target,d=(n??[t]).some(p=>{const h=XA(p)?p.current:p;return(h==null?void 0:h.contains(a))||h===a});o().activeElement!==a&&d&&(s.preventDefault(),a.focus())})}function Iw(e,t){return e?e===t||e.contains(t):!1}function n9(e={}){const{onChange:t,onCancel:n,onSubmit:r,onBlur:o,value:s,isDisabled:a,defaultValue:c,startWithEditView:d,isPreviewFocusable:p=!0,submitOnBlur:h=!0,selectAllOnFocus:m=!0,placeholder:v,onEdit:b,finalFocusRef:w,...y}=e,S=rr(b),k=!!(d&&!a),[_,I]=f.useState(k),[P,E]=Ac({defaultValue:c||"",value:s,onChange:t}),[O,R]=f.useState(P),M=f.useRef(null),T=f.useRef(null),A=f.useRef(null),$=f.useRef(null),Q=f.useRef(null);Q3({ref:M,enabled:_,elements:[$,Q]});const B=!_&&!a;Zl(()=>{var oe,pe;_&&((oe=M.current)==null||oe.focus(),m&&((pe=M.current)==null||pe.select()))},[]),Ba(()=>{var oe,pe,le,ge;if(!_){w?(oe=w.current)==null||oe.focus():(pe=A.current)==null||pe.focus();return}(le=M.current)==null||le.focus(),m&&((ge=M.current)==null||ge.select()),S==null||S()},[_,S,m]);const V=f.useCallback(()=>{B&&I(!0)},[B]),q=f.useCallback(()=>{R(P)},[P]),G=f.useCallback(()=>{I(!1),E(O),n==null||n(O),o==null||o(O)},[n,o,E,O]),D=f.useCallback(()=>{I(!1),R(P),r==null||r(P),o==null||o(O)},[P,r,o,O]);f.useEffect(()=>{if(_)return;const oe=M.current;(oe==null?void 0:oe.ownerDocument.activeElement)===oe&&(oe==null||oe.blur())},[_]);const L=f.useCallback(oe=>{E(oe.currentTarget.value)},[E]),W=f.useCallback(oe=>{const pe=oe.key,ge={Escape:G,Enter:_e=>{!_e.shiftKey&&!_e.metaKey&&D()}}[pe];ge&&(oe.preventDefault(),ge(oe))},[G,D]),Y=f.useCallback(oe=>{const pe=oe.key,ge={Escape:G}[pe];ge&&(oe.preventDefault(),ge(oe))},[G]),ae=P.length===0,ye=f.useCallback(oe=>{var pe;if(!_)return;const le=oe.currentTarget.ownerDocument,ge=(pe=oe.relatedTarget)!=null?pe:le.activeElement,_e=Iw($.current,ge),ie=Iw(Q.current,ge);!_e&&!ie&&(h?D():G())},[h,D,G,_]),ue=f.useCallback((oe={},pe=null)=>{const le=B&&p?0:void 0;return{...oe,ref:cn(pe,T),children:ae?v:P,hidden:_,"aria-disabled":ns(a),tabIndex:le,onFocus:et(oe.onFocus,V,q)}},[a,_,B,p,ae,V,q,v,P]),X=f.useCallback((oe={},pe=null)=>({...oe,hidden:!_,placeholder:v,ref:cn(pe,M),disabled:a,"aria-disabled":ns(a),value:P,onBlur:et(oe.onBlur,ye),onChange:et(oe.onChange,L),onKeyDown:et(oe.onKeyDown,W),onFocus:et(oe.onFocus,q)}),[a,_,ye,L,W,q,v,P]),K=f.useCallback((oe={},pe=null)=>({...oe,hidden:!_,placeholder:v,ref:cn(pe,M),disabled:a,"aria-disabled":ns(a),value:P,onBlur:et(oe.onBlur,ye),onChange:et(oe.onChange,L),onKeyDown:et(oe.onKeyDown,Y),onFocus:et(oe.onFocus,q)}),[a,_,ye,L,Y,q,v,P]),U=f.useCallback((oe={},pe=null)=>({"aria-label":"Edit",...oe,type:"button",onClick:et(oe.onClick,V),ref:cn(pe,A),disabled:a}),[V,a]),se=f.useCallback((oe={},pe=null)=>({...oe,"aria-label":"Submit",ref:cn(Q,pe),type:"button",onClick:et(oe.onClick,D),disabled:a}),[D,a]),re=f.useCallback((oe={},pe=null)=>({"aria-label":"Cancel",id:"cancel",...oe,ref:cn($,pe),type:"button",onClick:et(oe.onClick,G),disabled:a}),[G,a]);return{isEditing:_,isDisabled:a,isValueEmpty:ae,value:P,onEdit:V,onCancel:G,onSubmit:D,getPreviewProps:ue,getInputProps:X,getTextareaProps:K,getEditButtonProps:U,getSubmitButtonProps:se,getCancelButtonProps:re,htmlProps:y}}var J3=Te(function(t,n){const r=Br("Editable",t),o=qn(t),{htmlProps:s,...a}=n9(o),{isEditing:c,onSubmit:d,onCancel:p,onEdit:h}=a,m=kt("chakra-editable",t.className),v=D1(t.children,{isEditing:c,onSubmit:d,onCancel:p,onEdit:h});return i.jsx(YA,{value:a,children:i.jsx(KA,{value:r,children:i.jsx(Ie.div,{ref:n,...s,className:m,children:v})})})});J3.displayName="Editable";var Z3={exports:{}},r9="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",o9=r9,s9=o9;function eP(){}function tP(){}tP.resetWarningCache=eP;var a9=function(){function e(r,o,s,a,c,d){if(d!==s9){var p=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw p.name="Invariant Violation",p}}e.isRequired=e;function t(){return e}var n={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:tP,resetWarningCache:eP};return n.PropTypes=n,n};Z3.exports=a9();var i9=Z3.exports;const zn=cd(i9);var Ev="data-focus-lock",nP="data-focus-lock-disabled",l9="data-no-focus-lock",c9="data-autofocus-inside",u9="data-no-autofocus";function d9(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function f9(e,t){var n=f.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}function rP(e,t){return f9(t||null,function(n){return e.forEach(function(r){return d9(r,n)})})}var p0={width:"1px",height:"0px",padding:0,overflow:"hidden",position:"fixed",top:"1px",left:"1px"},Qs=function(){return Qs=Object.assign||function(t){for(var n,r=1,o=arguments.length;r0&&s[s.length-1])&&(p[0]===6||p[0]===2)){n=0;continue}if(p[0]===3&&(!s||p[1]>s[0]&&p[1]0)&&!(o=r.next()).done;)s.push(o.value)}catch(c){a={error:c}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s}function Ov(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r=0}).sort(P9)},j9=["button:enabled","select:enabled","textarea:enabled","input:enabled","a[href]","area[href]","summary","iframe","object","embed","audio[controls]","video[controls]","[tabindex]","[contenteditable]","[autofocus]"],ib=j9.join(","),I9="".concat(ib,", [data-focus-guard]"),wP=function(e,t){return ia((e.shadowRoot||e).children).reduce(function(n,r){return n.concat(r.matches(t?I9:ib)?[r]:[],wP(r))},[])},E9=function(e,t){var n;return e instanceof HTMLIFrameElement&&(!((n=e.contentDocument)===null||n===void 0)&&n.body)?am([e.contentDocument.body],t):[e]},am=function(e,t){return e.reduce(function(n,r){var o,s=wP(r,t),a=(o=[]).concat.apply(o,s.map(function(c){return E9(c,t)}));return n.concat(a,r.parentNode?ia(r.parentNode.querySelectorAll(ib)).filter(function(c){return c===r}):[])},[])},O9=function(e){var t=e.querySelectorAll("[".concat(c9,"]"));return ia(t).map(function(n){return am([n])}).reduce(function(n,r){return n.concat(r)},[])},lb=function(e,t){return ia(e).filter(function(n){return mP(t,n)}).filter(function(n){return C9(n)})},Ow=function(e,t){return t===void 0&&(t=new Map),ia(e).filter(function(n){return gP(t,n)})},Mv=function(e,t,n){return xP(lb(am(e,n),t),!0,n)},Rw=function(e,t){return xP(lb(am(e),t),!1)},R9=function(e,t){return lb(O9(e),t)},oc=function(e,t){return e.shadowRoot?oc(e.shadowRoot,t):Object.getPrototypeOf(e).contains!==void 0&&Object.getPrototypeOf(e).contains.call(e,t)?!0:ia(e.children).some(function(n){var r;if(n instanceof HTMLIFrameElement){var o=(r=n.contentDocument)===null||r===void 0?void 0:r.body;return o?oc(o,t):!1}return oc(n,t)})},M9=function(e){for(var t=new Set,n=e.length,r=0;r0&&t.add(o),(s&Node.DOCUMENT_POSITION_CONTAINS)>0&&t.add(r)}return e.filter(function(a,c){return!t.has(c)})},SP=function(e){return e.parentNode?SP(e.parentNode):e},cb=function(e){var t=Fp(e);return t.filter(Boolean).reduce(function(n,r){var o=r.getAttribute(Ev);return n.push.apply(n,o?M9(ia(SP(r).querySelectorAll("[".concat(Ev,'="').concat(o,'"]:not([').concat(nP,'="disabled"])')))):[r]),n},[])},D9=function(e){try{return e()}catch{return}},Gu=function(e){if(e===void 0&&(e=document),!(!e||!e.activeElement)){var t=e.activeElement;return t.shadowRoot?Gu(t.shadowRoot):t instanceof HTMLIFrameElement&&D9(function(){return t.contentWindow.document})?Gu(t.contentWindow.document):t}},T9=function(e,t){return e===t},A9=function(e,t){return!!ia(e.querySelectorAll("iframe")).some(function(n){return T9(n,t)})},CP=function(e,t){return t===void 0&&(t=Gu(fP(e).ownerDocument)),!t||t.dataset&&t.dataset.focusGuard?!1:cb(e).some(function(n){return oc(n,t)||A9(n,t)})},N9=function(e){e===void 0&&(e=document);var t=Gu(e);return t?ia(e.querySelectorAll("[".concat(l9,"]"))).some(function(n){return oc(n,t)}):!1},$9=function(e,t){return t.filter(yP).filter(function(n){return n.name===e.name}).filter(function(n){return n.checked})[0]||e},ub=function(e,t){return yP(e)&&e.name?$9(e,t):e},z9=function(e){var t=new Set;return e.forEach(function(n){return t.add(ub(n,e))}),e.filter(function(n){return t.has(n)})},Mw=function(e){return e[0]&&e.length>1?ub(e[0],e):e[0]},Dw=function(e,t){return e.length>1?e.indexOf(ub(e[t],e)):t},kP="NEW_FOCUS",L9=function(e,t,n,r){var o=e.length,s=e[0],a=e[o-1],c=ab(n);if(!(n&&e.indexOf(n)>=0)){var d=n!==void 0?t.indexOf(n):-1,p=r?t.indexOf(r):d,h=r?e.indexOf(r):-1,m=d-p,v=t.indexOf(s),b=t.indexOf(a),w=z9(t),y=n!==void 0?w.indexOf(n):-1,S=y-(r?w.indexOf(r):d),k=Dw(e,0),_=Dw(e,o-1);if(d===-1||h===-1)return kP;if(!m&&h>=0)return h;if(d<=v&&c&&Math.abs(m)>1)return _;if(d>=b&&c&&Math.abs(m)>1)return k;if(m&&Math.abs(S)>1)return h;if(d<=v)return _;if(d>b)return k;if(m)return Math.abs(m)>1?h:(o+h+m)%o}},B9=function(e){return function(t){var n,r=(n=vP(t))===null||n===void 0?void 0:n.autofocus;return t.autofocus||r!==void 0&&r!=="false"||e.indexOf(t)>=0}},F9=function(e,t,n){var r=e.map(function(s){var a=s.node;return a}),o=Ow(r.filter(B9(n)));return o&&o.length?Mw(o):Mw(Ow(t))},Dv=function(e,t){return t===void 0&&(t=[]),t.push(e),e.parentNode&&Dv(e.parentNode.host||e.parentNode,t),t},h0=function(e,t){for(var n=Dv(e),r=Dv(t),o=0;o=0)return s}return!1},_P=function(e,t,n){var r=Fp(e),o=Fp(t),s=r[0],a=!1;return o.filter(Boolean).forEach(function(c){a=h0(a||c,c)||a,n.filter(Boolean).forEach(function(d){var p=h0(s,d);p&&(!a||oc(p,a)?a=p:a=h0(p,a))})}),a},H9=function(e,t){return e.reduce(function(n,r){return n.concat(R9(r,t))},[])},W9=function(e,t){var n=new Map;return t.forEach(function(r){return n.set(r.node,r)}),e.map(function(r){return n.get(r)}).filter(_9)},V9=function(e,t){var n=Gu(Fp(e).length>0?document:fP(e).ownerDocument),r=cb(e).filter(Hp),o=_P(n||e,e,r),s=new Map,a=Rw(r,s),c=Mv(r,s).filter(function(b){var w=b.node;return Hp(w)});if(!(!c[0]&&(c=a,!c[0]))){var d=Rw([o],s).map(function(b){var w=b.node;return w}),p=W9(d,c),h=p.map(function(b){var w=b.node;return w}),m=L9(h,d,n,t);if(m===kP){var v=F9(a,h,H9(r,s));if(v)return{node:v};console.warn("focus-lock: cannot find any node to move focus into");return}return m===void 0?m:p[m]}},U9=function(e){var t=cb(e).filter(Hp),n=_P(e,e,t),r=new Map,o=Mv([n],r,!0),s=Mv(t,r).filter(function(a){var c=a.node;return Hp(c)}).map(function(a){var c=a.node;return c});return o.map(function(a){var c=a.node,d=a.index;return{node:c,index:d,lockItem:s.indexOf(c)>=0,guard:ab(c)}})},G9=function(e,t){"focus"in e&&e.focus(t),"contentWindow"in e&&e.contentWindow&&e.contentWindow.focus()},m0=0,g0=!1,PP=function(e,t,n){n===void 0&&(n={});var r=V9(e,t);if(!g0&&r){if(m0>2){console.error("FocusLock: focus-fighting detected. Only one focus management system could be active. See https://github.com/theKashey/focus-lock/#focus-fighting"),g0=!0,setTimeout(function(){g0=!1},1);return}m0++,G9(r.node,n.focusOptions),m0--}};function db(e){setTimeout(e,1)}var q9=function(){return document&&document.activeElement===document.body},K9=function(){return q9()||N9()},sc=null,Kl=null,ac=null,qu=!1,Y9=function(){return!0},X9=function(t){return(sc.whiteList||Y9)(t)},Q9=function(t,n){ac={observerNode:t,portaledElement:n}},J9=function(t){return ac&&ac.portaledElement===t};function Tw(e,t,n,r){var o=null,s=e;do{var a=r[s];if(a.guard)a.node.dataset.focusAutoGuard&&(o=a);else if(a.lockItem){if(s!==e)return;o=null}else break}while((s+=n)!==t);o&&(o.node.tabIndex=0)}var Z9=function(t){return t&&"current"in t?t.current:t},eN=function(t){return t?!!qu:qu==="meanwhile"},tN=function e(t,n,r){return n&&(n.host===t&&(!n.activeElement||r.contains(n.activeElement))||n.parentNode&&e(t,n.parentNode,r))},nN=function(t,n){return n.some(function(r){return tN(t,r,r)})},Wp=function(){var t=!1;if(sc){var n=sc,r=n.observed,o=n.persistentFocus,s=n.autoFocus,a=n.shards,c=n.crossFrame,d=n.focusOptions,p=r||ac&&ac.portaledElement,h=document&&document.activeElement;if(p){var m=[p].concat(a.map(Z9).filter(Boolean));if((!h||X9(h))&&(o||eN(c)||!K9()||!Kl&&s)&&(p&&!(CP(m)||h&&nN(h,m)||J9(h))&&(document&&!Kl&&h&&!s?(h.blur&&h.blur(),document.body.focus()):(t=PP(m,Kl,{focusOptions:d}),ac={})),qu=!1,Kl=document&&document.activeElement),document){var v=document&&document.activeElement,b=U9(m),w=b.map(function(y){var S=y.node;return S}).indexOf(v);w>-1&&(b.filter(function(y){var S=y.guard,k=y.node;return S&&k.dataset.focusAutoGuard}).forEach(function(y){var S=y.node;return S.removeAttribute("tabIndex")}),Tw(w,b.length,1,b),Tw(w,-1,-1,b))}}}return t},jP=function(t){Wp()&&t&&(t.stopPropagation(),t.preventDefault())},fb=function(){return db(Wp)},rN=function(t){var n=t.target,r=t.currentTarget;r.contains(n)||Q9(r,n)},oN=function(){return null},IP=function(){qu="just",db(function(){qu="meanwhile"})},sN=function(){document.addEventListener("focusin",jP),document.addEventListener("focusout",fb),window.addEventListener("blur",IP)},aN=function(){document.removeEventListener("focusin",jP),document.removeEventListener("focusout",fb),window.removeEventListener("blur",IP)};function iN(e){return e.filter(function(t){var n=t.disabled;return!n})}function lN(e){var t=e.slice(-1)[0];t&&!sc&&sN();var n=sc,r=n&&t&&t.id===n.id;sc=t,n&&!r&&(n.onDeactivation(),e.filter(function(o){var s=o.id;return s===n.id}).length||n.returnFocus(!t)),t?(Kl=null,(!r||n.observed!==t.observed)&&t.onActivation(),Wp(),db(Wp)):(aN(),Kl=null)}cP.assignSyncMedium(rN);uP.assignMedium(fb);h9.assignMedium(function(e){return e({moveFocusInside:PP,focusInside:CP})});const cN=b9(iN,lN)(oN);var EP=f.forwardRef(function(t,n){return f.createElement(dP,or({sideCar:cN,ref:n},t))}),OP=dP.propTypes||{};OP.sideCar;LD(OP,["sideCar"]);EP.propTypes={};const Aw=EP;function RP(e){return e!=null&&typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.ELEMENT_NODE}function pb(e){var t;if(!RP(e))return!1;const n=(t=e.ownerDocument.defaultView)!=null?t:window;return e instanceof n.HTMLElement}function uN(e){var t,n;return(n=(t=MP(e))==null?void 0:t.defaultView)!=null?n:window}function MP(e){return RP(e)?e.ownerDocument:document}function dN(e){return MP(e).activeElement}function fN(e){const t=e.ownerDocument.defaultView||window,{overflow:n,overflowX:r,overflowY:o}=t.getComputedStyle(e);return/auto|scroll|overlay|hidden/.test(n+o+r)}function pN(e){return e.localName==="html"?e:e.assignedSlot||e.parentElement||e.ownerDocument.documentElement}function DP(e){return["html","body","#document"].includes(e.localName)?e.ownerDocument.body:pb(e)&&fN(e)?e:DP(pN(e))}var TP=e=>e.hasAttribute("tabindex"),hN=e=>TP(e)&&e.tabIndex===-1;function mN(e){return!!e.getAttribute("disabled")||!!e.getAttribute("aria-disabled")}function AP(e){return e.parentElement&&AP(e.parentElement)?!0:e.hidden}function gN(e){const t=e.getAttribute("contenteditable");return t!=="false"&&t!=null}function NP(e){if(!pb(e)||AP(e)||mN(e))return!1;const{localName:t}=e;if(["input","select","textarea","button"].indexOf(t)>=0)return!0;const r={a:()=>e.hasAttribute("href"),audio:()=>e.hasAttribute("controls"),video:()=>e.hasAttribute("controls")};return t in r?r[t]():gN(e)?!0:TP(e)}function vN(e){return e?pb(e)&&NP(e)&&!hN(e):!1}var bN=["input:not(:disabled):not([disabled])","select:not(:disabled):not([disabled])","textarea:not(:disabled):not([disabled])","embed","iframe","object","a[href]","area[href]","button:not(:disabled):not([disabled])","[tabindex]","audio[controls]","video[controls]","*[tabindex]:not([aria-disabled])","*[contenteditable]"],yN=bN.join(),xN=e=>e.offsetWidth>0&&e.offsetHeight>0;function $P(e){const t=Array.from(e.querySelectorAll(yN));return t.unshift(e),t.filter(n=>NP(n)&&xN(n))}var Nw,wN=(Nw=Aw.default)!=null?Nw:Aw,zP=e=>{const{initialFocusRef:t,finalFocusRef:n,contentRef:r,restoreFocus:o,children:s,isDisabled:a,autoFocus:c,persistentFocus:d,lockFocusAcrossFrames:p}=e,h=f.useCallback(()=>{t!=null&&t.current?t.current.focus():r!=null&&r.current&&$P(r.current).length===0&&requestAnimationFrame(()=>{var w;(w=r.current)==null||w.focus()})},[t,r]),m=f.useCallback(()=>{var b;(b=n==null?void 0:n.current)==null||b.focus()},[n]),v=o&&!n;return i.jsx(wN,{crossFrame:p,persistentFocus:d,autoFocus:c,disabled:a,onActivation:h,onDeactivation:m,returnFocus:v,children:s})};zP.displayName="FocusLock";function SN(e,t,n,r){const o=C_(t);return f.useEffect(()=>{var s;const a=(s=j2(n))!=null?s:document;if(t)return a.addEventListener(e,o,r),()=>{a.removeEventListener(e,o,r)}},[e,n,r,o,t]),()=>{var s;((s=j2(n))!=null?s:document).removeEventListener(e,o,r)}}function CN(e){const{ref:t,handler:n,enabled:r=!0}=e,o=C_(n),a=f.useRef({isPointerDown:!1,ignoreEmulatedMouseEvents:!1}).current;f.useEffect(()=>{if(!r)return;const c=m=>{v0(m,t)&&(a.isPointerDown=!0)},d=m=>{if(a.ignoreEmulatedMouseEvents){a.ignoreEmulatedMouseEvents=!1;return}a.isPointerDown&&n&&v0(m,t)&&(a.isPointerDown=!1,o(m))},p=m=>{a.ignoreEmulatedMouseEvents=!0,n&&a.isPointerDown&&v0(m,t)&&(a.isPointerDown=!1,o(m))},h=k_(t.current);return h.addEventListener("mousedown",c,!0),h.addEventListener("mouseup",d,!0),h.addEventListener("touchstart",c,!0),h.addEventListener("touchend",p,!0),()=>{h.removeEventListener("mousedown",c,!0),h.removeEventListener("mouseup",d,!0),h.removeEventListener("touchstart",c,!0),h.removeEventListener("touchend",p,!0)}},[n,t,o,a,r])}function v0(e,t){var n;const r=e.target;return r&&!k_(r).contains(r)?!1:!((n=t.current)!=null&&n.contains(r))}var[kN,_N]=Rn({name:"InputGroupStylesContext",errorMessage:`useInputGroupStyles returned is 'undefined'. Seems you forgot to wrap the components in "" `}),LP=Te(function(t,n){const r=Br("Input",t),{children:o,className:s,...a}=qn(t),c=kt("chakra-input__group",s),d={},p=gd(o),h=r.field;p.forEach(v=>{var b,w;r&&(h&&v.type.id==="InputLeftElement"&&(d.paddingStart=(b=h.height)!=null?b:h.h),h&&v.type.id==="InputRightElement"&&(d.paddingEnd=(w=h.height)!=null?w:h.h),v.type.id==="InputRightAddon"&&(d.borderEndRadius=0),v.type.id==="InputLeftAddon"&&(d.borderStartRadius=0))});const m=p.map(v=>{var b,w;const y=Y1({size:((b=v.props)==null?void 0:b.size)||t.size,variant:((w=v.props)==null?void 0:w.variant)||t.variant});return v.type.id!=="Input"?f.cloneElement(v,y):f.cloneElement(v,Object.assign(y,d,v.props))});return i.jsx(Ie.div,{className:c,ref:n,__css:{width:"100%",display:"flex",position:"relative",isolation:"isolate"},"data-group":!0,...a,children:i.jsx(kN,{value:r,children:m})})});LP.displayName="InputGroup";var PN=Ie("div",{baseStyle:{display:"flex",alignItems:"center",justifyContent:"center",position:"absolute",top:"0",zIndex:2}}),im=Te(function(t,n){var r,o;const{placement:s="left",...a}=t,c=_N(),d=c.field,h={[s==="left"?"insetStart":"insetEnd"]:"0",width:(r=d==null?void 0:d.height)!=null?r:d==null?void 0:d.h,height:(o=d==null?void 0:d.height)!=null?o:d==null?void 0:d.h,fontSize:d==null?void 0:d.fontSize,...c.element};return i.jsx(PN,{ref:n,__css:h,...a})});im.id="InputElement";im.displayName="InputElement";var BP=Te(function(t,n){const{className:r,...o}=t,s=kt("chakra-input__left-element",r);return i.jsx(im,{ref:n,placement:"left",className:s,...o})});BP.id="InputLeftElement";BP.displayName="InputLeftElement";var hb=Te(function(t,n){const{className:r,...o}=t,s=kt("chakra-input__right-element",r);return i.jsx(im,{ref:n,placement:"right",className:s,...o})});hb.id="InputRightElement";hb.displayName="InputRightElement";var yd=Te(function(t,n){const{htmlSize:r,...o}=t,s=Br("Input",o),a=qn(o),c=Z1(a),d=kt("chakra-input",t.className);return i.jsx(Ie.input,{size:r,...c,__css:s.field,ref:n,className:d})});yd.displayName="Input";yd.id="Input";var mb=Te(function(t,n){const r=$a("Link",t),{className:o,isExternal:s,...a}=qn(t);return i.jsx(Ie.a,{target:s?"_blank":void 0,rel:s?"noopener":void 0,ref:n,className:kt("chakra-link",o),...a,__css:r})});mb.displayName="Link";var[jN,FP]=Rn({name:"ListStylesContext",errorMessage:`useListStyles returned is 'undefined'. Seems you forgot to wrap the components in "" `}),gb=Te(function(t,n){const r=Br("List",t),{children:o,styleType:s="none",stylePosition:a,spacing:c,...d}=qn(t),p=gd(o),m=c?{["& > *:not(style) ~ *:not(style)"]:{mt:c}}:{};return i.jsx(jN,{value:r,children:i.jsx(Ie.ul,{ref:n,listStyleType:s,listStylePosition:a,role:"list",__css:{...r.container,...m},...d,children:p})})});gb.displayName="List";var IN=Te((e,t)=>{const{as:n,...r}=e;return i.jsx(gb,{ref:t,as:"ol",styleType:"decimal",marginStart:"1em",...r})});IN.displayName="OrderedList";var vb=Te(function(t,n){const{as:r,...o}=t;return i.jsx(gb,{ref:n,as:"ul",styleType:"initial",marginStart:"1em",...o})});vb.displayName="UnorderedList";var xa=Te(function(t,n){const r=FP();return i.jsx(Ie.li,{ref:n,...t,__css:r.item})});xa.displayName="ListItem";var EN=Te(function(t,n){const r=FP();return i.jsx(Kr,{ref:n,role:"presentation",...t,__css:r.icon})});EN.displayName="ListIcon";var rl=Te(function(t,n){const{templateAreas:r,gap:o,rowGap:s,columnGap:a,column:c,row:d,autoFlow:p,autoRows:h,templateRows:m,autoColumns:v,templateColumns:b,...w}=t,y={display:"grid",gridTemplateAreas:r,gridGap:o,gridRowGap:s,gridColumnGap:a,gridAutoColumns:v,gridColumn:c,gridRow:d,gridAutoFlow:p,gridAutoRows:h,gridTemplateRows:m,gridTemplateColumns:b};return i.jsx(Ie.div,{ref:n,__css:y,...w})});rl.displayName="Grid";function HP(e,t){return Array.isArray(e)?e.map(n=>n===null?null:t(n)):pv(e)?Object.keys(e).reduce((n,r)=>(n[r]=t(e[r]),n),{}):e!=null?t(e):null}var fl=Ie("div",{baseStyle:{flex:1,justifySelf:"stretch",alignSelf:"stretch"}});fl.displayName="Spacer";var tt=Te(function(t,n){const r=$a("Text",t),{className:o,align:s,decoration:a,casing:c,...d}=qn(t),p=Y1({textAlign:t.align,textDecoration:t.decoration,textTransform:t.casing});return i.jsx(Ie.p,{ref:n,className:kt("chakra-text",t.className),...p,...d,__css:r})});tt.displayName="Text";var WP=e=>i.jsx(Ie.div,{className:"chakra-stack__item",...e,__css:{display:"inline-block",flex:"0 0 auto",minWidth:0,...e.__css}});WP.displayName="StackItem";function ON(e){const{spacing:t,direction:n}=e,r={column:{my:t,mx:0,borderLeftWidth:0,borderBottomWidth:"1px"},"column-reverse":{my:t,mx:0,borderLeftWidth:0,borderBottomWidth:"1px"},row:{mx:t,my:0,borderLeftWidth:"1px",borderBottomWidth:0},"row-reverse":{mx:t,my:0,borderLeftWidth:"1px",borderBottomWidth:0}};return{"&":HP(n,o=>r[o])}}var bb=Te((e,t)=>{const{isInline:n,direction:r,align:o,justify:s,spacing:a="0.5rem",wrap:c,children:d,divider:p,className:h,shouldWrapChildren:m,...v}=e,b=n?"row":r??"column",w=f.useMemo(()=>ON({spacing:a,direction:b}),[a,b]),y=!!p,S=!m&&!y,k=f.useMemo(()=>{const I=gd(d);return S?I:I.map((P,E)=>{const O=typeof P.key<"u"?P.key:E,R=E+1===I.length,T=m?i.jsx(WP,{children:P},O):P;if(!y)return T;const A=f.cloneElement(p,{__css:w}),$=R?null:A;return i.jsxs(f.Fragment,{children:[T,$]},O)})},[p,w,y,S,m,d]),_=kt("chakra-stack",h);return i.jsx(Ie.div,{ref:t,display:"flex",alignItems:o,justifyContent:s,flexDirection:b,flexWrap:c,gap:y?void 0:a,className:_,...v,children:k})});bb.displayName="Stack";var VP=Te((e,t)=>i.jsx(bb,{align:"center",...e,direction:"column",ref:t}));VP.displayName="VStack";var di=Te((e,t)=>i.jsx(bb,{align:"center",...e,direction:"row",ref:t}));di.displayName="HStack";function $w(e){return HP(e,t=>t==="auto"?"auto":`span ${t}/span ${t}`)}var Tv=Te(function(t,n){const{area:r,colSpan:o,colStart:s,colEnd:a,rowEnd:c,rowSpan:d,rowStart:p,...h}=t,m=Y1({gridArea:r,gridColumn:$w(o),gridRow:$w(d),gridColumnStart:s,gridColumnEnd:a,gridRowStart:p,gridRowEnd:c});return i.jsx(Ie.div,{ref:n,__css:m,...h})});Tv.displayName="GridItem";var pl=Te(function(t,n){const r=$a("Badge",t),{className:o,...s}=qn(t);return i.jsx(Ie.span,{ref:n,className:kt("chakra-badge",t.className),...s,__css:{display:"inline-block",whiteSpace:"nowrap",verticalAlign:"middle",...r}})});pl.displayName="Badge";var hl=Te(function(t,n){const{borderLeftWidth:r,borderBottomWidth:o,borderTopWidth:s,borderRightWidth:a,borderWidth:c,borderStyle:d,borderColor:p,...h}=$a("Divider",t),{className:m,orientation:v="horizontal",__css:b,...w}=qn(t),y={vertical:{borderLeftWidth:r||a||c||"1px",height:"100%"},horizontal:{borderBottomWidth:o||s||c||"1px",width:"100%"}};return i.jsx(Ie.hr,{ref:n,"aria-orientation":v,...w,__css:{...h,border:"0",borderColor:p,borderStyle:d,...y[v],...b},className:kt("chakra-divider",m)})});hl.displayName="Divider";function RN(e){const{key:t}=e;return t.length===1||t.length>1&&/[^a-zA-Z0-9]/.test(t)}function MN(e={}){const{timeout:t=300,preventDefault:n=()=>!0}=e,[r,o]=f.useState([]),s=f.useRef(),a=()=>{s.current&&(clearTimeout(s.current),s.current=null)},c=()=>{a(),s.current=setTimeout(()=>{o([]),s.current=null},t)};f.useEffect(()=>a,[]);function d(p){return h=>{if(h.key==="Backspace"){const m=[...r];m.pop(),o(m);return}if(RN(h)){const m=r.concat(h.key);n(h)&&(h.preventDefault(),h.stopPropagation()),o(m),p(m.join("")),c()}}}return d}function DN(e,t,n,r){if(t==null)return r;if(!r)return e.find(a=>n(a).toLowerCase().startsWith(t.toLowerCase()));const o=e.filter(s=>n(s).toLowerCase().startsWith(t.toLowerCase()));if(o.length>0){let s;return o.includes(r)?(s=o.indexOf(r)+1,s===o.length&&(s=0),o[s]):(s=e.indexOf(o[0]),e[s])}return r}function TN(){const e=f.useRef(new Map),t=e.current,n=f.useCallback((o,s,a,c)=>{e.current.set(a,{type:s,el:o,options:c}),o.addEventListener(s,a,c)},[]),r=f.useCallback((o,s,a,c)=>{o.removeEventListener(s,a,c),e.current.delete(a)},[]);return f.useEffect(()=>()=>{t.forEach((o,s)=>{r(o.el,o.type,s,o.options)})},[r,t]),{add:n,remove:r}}function b0(e){const t=e.target,{tagName:n,isContentEditable:r}=t;return n!=="INPUT"&&n!=="TEXTAREA"&&r!==!0}function UP(e={}){const{ref:t,isDisabled:n,isFocusable:r,clickOnEnter:o=!0,clickOnSpace:s=!0,onMouseDown:a,onMouseUp:c,onClick:d,onKeyDown:p,onKeyUp:h,tabIndex:m,onMouseOver:v,onMouseLeave:b,...w}=e,[y,S]=f.useState(!0),[k,_]=f.useState(!1),I=TN(),P=D=>{D&&D.tagName!=="BUTTON"&&S(!1)},E=y?m:m||0,O=n&&!r,R=f.useCallback(D=>{if(n){D.stopPropagation(),D.preventDefault();return}D.currentTarget.focus(),d==null||d(D)},[n,d]),M=f.useCallback(D=>{k&&b0(D)&&(D.preventDefault(),D.stopPropagation(),_(!1),I.remove(document,"keyup",M,!1))},[k,I]),T=f.useCallback(D=>{if(p==null||p(D),n||D.defaultPrevented||D.metaKey||!b0(D.nativeEvent)||y)return;const L=o&&D.key==="Enter";s&&D.key===" "&&(D.preventDefault(),_(!0)),L&&(D.preventDefault(),D.currentTarget.click()),I.add(document,"keyup",M,!1)},[n,y,p,o,s,I,M]),A=f.useCallback(D=>{if(h==null||h(D),n||D.defaultPrevented||D.metaKey||!b0(D.nativeEvent)||y)return;s&&D.key===" "&&(D.preventDefault(),_(!1),D.currentTarget.click())},[s,y,n,h]),$=f.useCallback(D=>{D.button===0&&(_(!1),I.remove(document,"mouseup",$,!1))},[I]),Q=f.useCallback(D=>{if(D.button!==0)return;if(n){D.stopPropagation(),D.preventDefault();return}y||_(!0),D.currentTarget.focus({preventScroll:!0}),I.add(document,"mouseup",$,!1),a==null||a(D)},[n,y,a,I,$]),B=f.useCallback(D=>{D.button===0&&(y||_(!1),c==null||c(D))},[c,y]),V=f.useCallback(D=>{if(n){D.preventDefault();return}v==null||v(D)},[n,v]),q=f.useCallback(D=>{k&&(D.preventDefault(),_(!1)),b==null||b(D)},[k,b]),G=cn(t,P);return y?{...w,ref:G,type:"button","aria-disabled":O?void 0:n,disabled:O,onClick:R,onMouseDown:a,onMouseUp:c,onKeyUp:h,onKeyDown:p,onMouseOver:v,onMouseLeave:b}:{...w,ref:G,role:"button","data-active":tn(k),"aria-disabled":n?"true":void 0,tabIndex:O?void 0:E,onClick:R,onMouseDown:Q,onMouseUp:B,onKeyUp:A,onKeyDown:T,onMouseOver:V,onMouseLeave:q}}function AN(e){const t=e.current;if(!t)return!1;const n=dN(t);return!n||t.contains(n)?!1:!!vN(n)}function GP(e,t){const{shouldFocus:n,visible:r,focusRef:o}=t,s=n&&!r;Ba(()=>{if(!s||AN(e))return;const a=(o==null?void 0:o.current)||e.current;let c;if(a)return c=requestAnimationFrame(()=>{a.focus({preventScroll:!0})}),()=>{cancelAnimationFrame(c)}},[s,e,o])}var NN={preventScroll:!0,shouldFocus:!1};function $N(e,t=NN){const{focusRef:n,preventScroll:r,shouldFocus:o,visible:s}=t,a=zN(e)?e.current:e,c=o&&s,d=f.useRef(c),p=f.useRef(s);Zl(()=>{!p.current&&s&&(d.current=c),p.current=s},[s,c]);const h=f.useCallback(()=>{if(!(!s||!a||!d.current)&&(d.current=!1,!a.contains(document.activeElement)))if(n!=null&&n.current)requestAnimationFrame(()=>{var m;(m=n.current)==null||m.focus({preventScroll:r})});else{const m=$P(a);m.length>0&&requestAnimationFrame(()=>{m[0].focus({preventScroll:r})})}},[s,r,a,n]);Ba(()=>{h()},[h]),Yi(a,"transitionend",h)}function zN(e){return"current"in e}var Tl=(e,t)=>({var:e,varRef:t?`var(${e}, ${t})`:`var(${e})`}),Pr={arrowShadowColor:Tl("--popper-arrow-shadow-color"),arrowSize:Tl("--popper-arrow-size","8px"),arrowSizeHalf:Tl("--popper-arrow-size-half"),arrowBg:Tl("--popper-arrow-bg"),transformOrigin:Tl("--popper-transform-origin"),arrowOffset:Tl("--popper-arrow-offset")};function LN(e){if(e.includes("top"))return"1px 1px 0px 0 var(--popper-arrow-shadow-color)";if(e.includes("bottom"))return"-1px -1px 0px 0 var(--popper-arrow-shadow-color)";if(e.includes("right"))return"-1px 1px 0px 0 var(--popper-arrow-shadow-color)";if(e.includes("left"))return"1px -1px 0px 0 var(--popper-arrow-shadow-color)"}var BN={top:"bottom center","top-start":"bottom left","top-end":"bottom right",bottom:"top center","bottom-start":"top left","bottom-end":"top right",left:"right center","left-start":"right top","left-end":"right bottom",right:"left center","right-start":"left top","right-end":"left bottom"},FN=e=>BN[e],zw={scroll:!0,resize:!0};function HN(e){let t;return typeof e=="object"?t={enabled:!0,options:{...zw,...e}}:t={enabled:e,options:zw},t}var WN={name:"matchWidth",enabled:!0,phase:"beforeWrite",requires:["computeStyles"],fn:({state:e})=>{e.styles.popper.width=`${e.rects.reference.width}px`},effect:({state:e})=>()=>{const t=e.elements.reference;e.elements.popper.style.width=`${t.offsetWidth}px`}},VN={name:"transformOrigin",enabled:!0,phase:"write",fn:({state:e})=>{Lw(e)},effect:({state:e})=>()=>{Lw(e)}},Lw=e=>{e.elements.popper.style.setProperty(Pr.transformOrigin.var,FN(e.placement))},UN={name:"positionArrow",enabled:!0,phase:"afterWrite",fn:({state:e})=>{GN(e)}},GN=e=>{var t;if(!e.placement)return;const n=qN(e.placement);if((t=e.elements)!=null&&t.arrow&&n){Object.assign(e.elements.arrow.style,{[n.property]:n.value,width:Pr.arrowSize.varRef,height:Pr.arrowSize.varRef,zIndex:-1});const r={[Pr.arrowSizeHalf.var]:`calc(${Pr.arrowSize.varRef} / 2 - 1px)`,[Pr.arrowOffset.var]:`calc(${Pr.arrowSizeHalf.varRef} * -1)`};for(const o in r)e.elements.arrow.style.setProperty(o,r[o])}},qN=e=>{if(e.startsWith("top"))return{property:"bottom",value:Pr.arrowOffset.varRef};if(e.startsWith("bottom"))return{property:"top",value:Pr.arrowOffset.varRef};if(e.startsWith("left"))return{property:"right",value:Pr.arrowOffset.varRef};if(e.startsWith("right"))return{property:"left",value:Pr.arrowOffset.varRef}},KN={name:"innerArrow",enabled:!0,phase:"main",requires:["arrow"],fn:({state:e})=>{Bw(e)},effect:({state:e})=>()=>{Bw(e)}},Bw=e=>{if(!e.elements.arrow)return;const t=e.elements.arrow.querySelector("[data-popper-arrow-inner]");if(!t)return;const n=LN(e.placement);n&&t.style.setProperty("--popper-arrow-default-shadow",n),Object.assign(t.style,{transform:"rotate(45deg)",background:Pr.arrowBg.varRef,top:0,left:0,width:"100%",height:"100%",position:"absolute",zIndex:"inherit",boxShadow:"var(--popper-arrow-shadow, var(--popper-arrow-default-shadow))"})},YN={"start-start":{ltr:"left-start",rtl:"right-start"},"start-end":{ltr:"left-end",rtl:"right-end"},"end-start":{ltr:"right-start",rtl:"left-start"},"end-end":{ltr:"right-end",rtl:"left-end"},start:{ltr:"left",rtl:"right"},end:{ltr:"right",rtl:"left"}},XN={"auto-start":"auto-end","auto-end":"auto-start","top-start":"top-end","top-end":"top-start","bottom-start":"bottom-end","bottom-end":"bottom-start"};function QN(e,t="ltr"){var n,r;const o=((n=YN[e])==null?void 0:n[t])||e;return t==="ltr"?o:(r=XN[e])!=null?r:o}var Co="top",as="bottom",is="right",ko="left",yb="auto",xd=[Co,as,is,ko],vc="start",Ku="end",JN="clippingParents",qP="viewport",du="popper",ZN="reference",Fw=xd.reduce(function(e,t){return e.concat([t+"-"+vc,t+"-"+Ku])},[]),KP=[].concat(xd,[yb]).reduce(function(e,t){return e.concat([t,t+"-"+vc,t+"-"+Ku])},[]),e$="beforeRead",t$="read",n$="afterRead",r$="beforeMain",o$="main",s$="afterMain",a$="beforeWrite",i$="write",l$="afterWrite",c$=[e$,t$,n$,r$,o$,s$,a$,i$,l$];function ra(e){return e?(e.nodeName||"").toLowerCase():null}function Lo(e){if(e==null)return window;if(e.toString()!=="[object Window]"){var t=e.ownerDocument;return t&&t.defaultView||window}return e}function ol(e){var t=Lo(e).Element;return e instanceof t||e instanceof Element}function rs(e){var t=Lo(e).HTMLElement;return e instanceof t||e instanceof HTMLElement}function xb(e){if(typeof ShadowRoot>"u")return!1;var t=Lo(e).ShadowRoot;return e instanceof t||e instanceof ShadowRoot}function u$(e){var t=e.state;Object.keys(t.elements).forEach(function(n){var r=t.styles[n]||{},o=t.attributes[n]||{},s=t.elements[n];!rs(s)||!ra(s)||(Object.assign(s.style,r),Object.keys(o).forEach(function(a){var c=o[a];c===!1?s.removeAttribute(a):s.setAttribute(a,c===!0?"":c)}))})}function d$(e){var t=e.state,n={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(t.elements.popper.style,n.popper),t.styles=n,t.elements.arrow&&Object.assign(t.elements.arrow.style,n.arrow),function(){Object.keys(t.elements).forEach(function(r){var o=t.elements[r],s=t.attributes[r]||{},a=Object.keys(t.styles.hasOwnProperty(r)?t.styles[r]:n[r]),c=a.reduce(function(d,p){return d[p]="",d},{});!rs(o)||!ra(o)||(Object.assign(o.style,c),Object.keys(s).forEach(function(d){o.removeAttribute(d)}))})}}const f$={name:"applyStyles",enabled:!0,phase:"write",fn:u$,effect:d$,requires:["computeStyles"]};function ta(e){return e.split("-")[0]}var Xi=Math.max,Vp=Math.min,bc=Math.round;function Av(){var e=navigator.userAgentData;return e!=null&&e.brands&&Array.isArray(e.brands)?e.brands.map(function(t){return t.brand+"/"+t.version}).join(" "):navigator.userAgent}function YP(){return!/^((?!chrome|android).)*safari/i.test(Av())}function yc(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!1);var r=e.getBoundingClientRect(),o=1,s=1;t&&rs(e)&&(o=e.offsetWidth>0&&bc(r.width)/e.offsetWidth||1,s=e.offsetHeight>0&&bc(r.height)/e.offsetHeight||1);var a=ol(e)?Lo(e):window,c=a.visualViewport,d=!YP()&&n,p=(r.left+(d&&c?c.offsetLeft:0))/o,h=(r.top+(d&&c?c.offsetTop:0))/s,m=r.width/o,v=r.height/s;return{width:m,height:v,top:h,right:p+m,bottom:h+v,left:p,x:p,y:h}}function wb(e){var t=yc(e),n=e.offsetWidth,r=e.offsetHeight;return Math.abs(t.width-n)<=1&&(n=t.width),Math.abs(t.height-r)<=1&&(r=t.height),{x:e.offsetLeft,y:e.offsetTop,width:n,height:r}}function XP(e,t){var n=t.getRootNode&&t.getRootNode();if(e.contains(t))return!0;if(n&&xb(n)){var r=t;do{if(r&&e.isSameNode(r))return!0;r=r.parentNode||r.host}while(r)}return!1}function Ea(e){return Lo(e).getComputedStyle(e)}function p$(e){return["table","td","th"].indexOf(ra(e))>=0}function Pi(e){return((ol(e)?e.ownerDocument:e.document)||window.document).documentElement}function lm(e){return ra(e)==="html"?e:e.assignedSlot||e.parentNode||(xb(e)?e.host:null)||Pi(e)}function Hw(e){return!rs(e)||Ea(e).position==="fixed"?null:e.offsetParent}function h$(e){var t=/firefox/i.test(Av()),n=/Trident/i.test(Av());if(n&&rs(e)){var r=Ea(e);if(r.position==="fixed")return null}var o=lm(e);for(xb(o)&&(o=o.host);rs(o)&&["html","body"].indexOf(ra(o))<0;){var s=Ea(o);if(s.transform!=="none"||s.perspective!=="none"||s.contain==="paint"||["transform","perspective"].indexOf(s.willChange)!==-1||t&&s.willChange==="filter"||t&&s.filter&&s.filter!=="none")return o;o=o.parentNode}return null}function wd(e){for(var t=Lo(e),n=Hw(e);n&&p$(n)&&Ea(n).position==="static";)n=Hw(n);return n&&(ra(n)==="html"||ra(n)==="body"&&Ea(n).position==="static")?t:n||h$(e)||t}function Sb(e){return["top","bottom"].indexOf(e)>=0?"x":"y"}function Tu(e,t,n){return Xi(e,Vp(t,n))}function m$(e,t,n){var r=Tu(e,t,n);return r>n?n:r}function QP(){return{top:0,right:0,bottom:0,left:0}}function JP(e){return Object.assign({},QP(),e)}function ZP(e,t){return t.reduce(function(n,r){return n[r]=e,n},{})}var g$=function(t,n){return t=typeof t=="function"?t(Object.assign({},n.rects,{placement:n.placement})):t,JP(typeof t!="number"?t:ZP(t,xd))};function v$(e){var t,n=e.state,r=e.name,o=e.options,s=n.elements.arrow,a=n.modifiersData.popperOffsets,c=ta(n.placement),d=Sb(c),p=[ko,is].indexOf(c)>=0,h=p?"height":"width";if(!(!s||!a)){var m=g$(o.padding,n),v=wb(s),b=d==="y"?Co:ko,w=d==="y"?as:is,y=n.rects.reference[h]+n.rects.reference[d]-a[d]-n.rects.popper[h],S=a[d]-n.rects.reference[d],k=wd(s),_=k?d==="y"?k.clientHeight||0:k.clientWidth||0:0,I=y/2-S/2,P=m[b],E=_-v[h]-m[w],O=_/2-v[h]/2+I,R=Tu(P,O,E),M=d;n.modifiersData[r]=(t={},t[M]=R,t.centerOffset=R-O,t)}}function b$(e){var t=e.state,n=e.options,r=n.element,o=r===void 0?"[data-popper-arrow]":r;o!=null&&(typeof o=="string"&&(o=t.elements.popper.querySelector(o),!o)||XP(t.elements.popper,o)&&(t.elements.arrow=o))}const y$={name:"arrow",enabled:!0,phase:"main",fn:v$,effect:b$,requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function xc(e){return e.split("-")[1]}var x$={top:"auto",right:"auto",bottom:"auto",left:"auto"};function w$(e,t){var n=e.x,r=e.y,o=t.devicePixelRatio||1;return{x:bc(n*o)/o||0,y:bc(r*o)/o||0}}function Ww(e){var t,n=e.popper,r=e.popperRect,o=e.placement,s=e.variation,a=e.offsets,c=e.position,d=e.gpuAcceleration,p=e.adaptive,h=e.roundOffsets,m=e.isFixed,v=a.x,b=v===void 0?0:v,w=a.y,y=w===void 0?0:w,S=typeof h=="function"?h({x:b,y}):{x:b,y};b=S.x,y=S.y;var k=a.hasOwnProperty("x"),_=a.hasOwnProperty("y"),I=ko,P=Co,E=window;if(p){var O=wd(n),R="clientHeight",M="clientWidth";if(O===Lo(n)&&(O=Pi(n),Ea(O).position!=="static"&&c==="absolute"&&(R="scrollHeight",M="scrollWidth")),O=O,o===Co||(o===ko||o===is)&&s===Ku){P=as;var T=m&&O===E&&E.visualViewport?E.visualViewport.height:O[R];y-=T-r.height,y*=d?1:-1}if(o===ko||(o===Co||o===as)&&s===Ku){I=is;var A=m&&O===E&&E.visualViewport?E.visualViewport.width:O[M];b-=A-r.width,b*=d?1:-1}}var $=Object.assign({position:c},p&&x$),Q=h===!0?w$({x:b,y},Lo(n)):{x:b,y};if(b=Q.x,y=Q.y,d){var B;return Object.assign({},$,(B={},B[P]=_?"0":"",B[I]=k?"0":"",B.transform=(E.devicePixelRatio||1)<=1?"translate("+b+"px, "+y+"px)":"translate3d("+b+"px, "+y+"px, 0)",B))}return Object.assign({},$,(t={},t[P]=_?y+"px":"",t[I]=k?b+"px":"",t.transform="",t))}function S$(e){var t=e.state,n=e.options,r=n.gpuAcceleration,o=r===void 0?!0:r,s=n.adaptive,a=s===void 0?!0:s,c=n.roundOffsets,d=c===void 0?!0:c,p={placement:ta(t.placement),variation:xc(t.placement),popper:t.elements.popper,popperRect:t.rects.popper,gpuAcceleration:o,isFixed:t.options.strategy==="fixed"};t.modifiersData.popperOffsets!=null&&(t.styles.popper=Object.assign({},t.styles.popper,Ww(Object.assign({},p,{offsets:t.modifiersData.popperOffsets,position:t.options.strategy,adaptive:a,roundOffsets:d})))),t.modifiersData.arrow!=null&&(t.styles.arrow=Object.assign({},t.styles.arrow,Ww(Object.assign({},p,{offsets:t.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:d})))),t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-placement":t.placement})}const C$={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:S$,data:{}};var Mf={passive:!0};function k$(e){var t=e.state,n=e.instance,r=e.options,o=r.scroll,s=o===void 0?!0:o,a=r.resize,c=a===void 0?!0:a,d=Lo(t.elements.popper),p=[].concat(t.scrollParents.reference,t.scrollParents.popper);return s&&p.forEach(function(h){h.addEventListener("scroll",n.update,Mf)}),c&&d.addEventListener("resize",n.update,Mf),function(){s&&p.forEach(function(h){h.removeEventListener("scroll",n.update,Mf)}),c&&d.removeEventListener("resize",n.update,Mf)}}const _$={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:k$,data:{}};var P$={left:"right",right:"left",bottom:"top",top:"bottom"};function yp(e){return e.replace(/left|right|bottom|top/g,function(t){return P$[t]})}var j$={start:"end",end:"start"};function Vw(e){return e.replace(/start|end/g,function(t){return j$[t]})}function Cb(e){var t=Lo(e),n=t.pageXOffset,r=t.pageYOffset;return{scrollLeft:n,scrollTop:r}}function kb(e){return yc(Pi(e)).left+Cb(e).scrollLeft}function I$(e,t){var n=Lo(e),r=Pi(e),o=n.visualViewport,s=r.clientWidth,a=r.clientHeight,c=0,d=0;if(o){s=o.width,a=o.height;var p=YP();(p||!p&&t==="fixed")&&(c=o.offsetLeft,d=o.offsetTop)}return{width:s,height:a,x:c+kb(e),y:d}}function E$(e){var t,n=Pi(e),r=Cb(e),o=(t=e.ownerDocument)==null?void 0:t.body,s=Xi(n.scrollWidth,n.clientWidth,o?o.scrollWidth:0,o?o.clientWidth:0),a=Xi(n.scrollHeight,n.clientHeight,o?o.scrollHeight:0,o?o.clientHeight:0),c=-r.scrollLeft+kb(e),d=-r.scrollTop;return Ea(o||n).direction==="rtl"&&(c+=Xi(n.clientWidth,o?o.clientWidth:0)-s),{width:s,height:a,x:c,y:d}}function _b(e){var t=Ea(e),n=t.overflow,r=t.overflowX,o=t.overflowY;return/auto|scroll|overlay|hidden/.test(n+o+r)}function e5(e){return["html","body","#document"].indexOf(ra(e))>=0?e.ownerDocument.body:rs(e)&&_b(e)?e:e5(lm(e))}function Au(e,t){var n;t===void 0&&(t=[]);var r=e5(e),o=r===((n=e.ownerDocument)==null?void 0:n.body),s=Lo(r),a=o?[s].concat(s.visualViewport||[],_b(r)?r:[]):r,c=t.concat(a);return o?c:c.concat(Au(lm(a)))}function Nv(e){return Object.assign({},e,{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height})}function O$(e,t){var n=yc(e,!1,t==="fixed");return n.top=n.top+e.clientTop,n.left=n.left+e.clientLeft,n.bottom=n.top+e.clientHeight,n.right=n.left+e.clientWidth,n.width=e.clientWidth,n.height=e.clientHeight,n.x=n.left,n.y=n.top,n}function Uw(e,t,n){return t===qP?Nv(I$(e,n)):ol(t)?O$(t,n):Nv(E$(Pi(e)))}function R$(e){var t=Au(lm(e)),n=["absolute","fixed"].indexOf(Ea(e).position)>=0,r=n&&rs(e)?wd(e):e;return ol(r)?t.filter(function(o){return ol(o)&&XP(o,r)&&ra(o)!=="body"}):[]}function M$(e,t,n,r){var o=t==="clippingParents"?R$(e):[].concat(t),s=[].concat(o,[n]),a=s[0],c=s.reduce(function(d,p){var h=Uw(e,p,r);return d.top=Xi(h.top,d.top),d.right=Vp(h.right,d.right),d.bottom=Vp(h.bottom,d.bottom),d.left=Xi(h.left,d.left),d},Uw(e,a,r));return c.width=c.right-c.left,c.height=c.bottom-c.top,c.x=c.left,c.y=c.top,c}function t5(e){var t=e.reference,n=e.element,r=e.placement,o=r?ta(r):null,s=r?xc(r):null,a=t.x+t.width/2-n.width/2,c=t.y+t.height/2-n.height/2,d;switch(o){case Co:d={x:a,y:t.y-n.height};break;case as:d={x:a,y:t.y+t.height};break;case is:d={x:t.x+t.width,y:c};break;case ko:d={x:t.x-n.width,y:c};break;default:d={x:t.x,y:t.y}}var p=o?Sb(o):null;if(p!=null){var h=p==="y"?"height":"width";switch(s){case vc:d[p]=d[p]-(t[h]/2-n[h]/2);break;case Ku:d[p]=d[p]+(t[h]/2-n[h]/2);break}}return d}function Yu(e,t){t===void 0&&(t={});var n=t,r=n.placement,o=r===void 0?e.placement:r,s=n.strategy,a=s===void 0?e.strategy:s,c=n.boundary,d=c===void 0?JN:c,p=n.rootBoundary,h=p===void 0?qP:p,m=n.elementContext,v=m===void 0?du:m,b=n.altBoundary,w=b===void 0?!1:b,y=n.padding,S=y===void 0?0:y,k=JP(typeof S!="number"?S:ZP(S,xd)),_=v===du?ZN:du,I=e.rects.popper,P=e.elements[w?_:v],E=M$(ol(P)?P:P.contextElement||Pi(e.elements.popper),d,h,a),O=yc(e.elements.reference),R=t5({reference:O,element:I,strategy:"absolute",placement:o}),M=Nv(Object.assign({},I,R)),T=v===du?M:O,A={top:E.top-T.top+k.top,bottom:T.bottom-E.bottom+k.bottom,left:E.left-T.left+k.left,right:T.right-E.right+k.right},$=e.modifiersData.offset;if(v===du&&$){var Q=$[o];Object.keys(A).forEach(function(B){var V=[is,as].indexOf(B)>=0?1:-1,q=[Co,as].indexOf(B)>=0?"y":"x";A[B]+=Q[q]*V})}return A}function D$(e,t){t===void 0&&(t={});var n=t,r=n.placement,o=n.boundary,s=n.rootBoundary,a=n.padding,c=n.flipVariations,d=n.allowedAutoPlacements,p=d===void 0?KP:d,h=xc(r),m=h?c?Fw:Fw.filter(function(w){return xc(w)===h}):xd,v=m.filter(function(w){return p.indexOf(w)>=0});v.length===0&&(v=m);var b=v.reduce(function(w,y){return w[y]=Yu(e,{placement:y,boundary:o,rootBoundary:s,padding:a})[ta(y)],w},{});return Object.keys(b).sort(function(w,y){return b[w]-b[y]})}function T$(e){if(ta(e)===yb)return[];var t=yp(e);return[Vw(e),t,Vw(t)]}function A$(e){var t=e.state,n=e.options,r=e.name;if(!t.modifiersData[r]._skip){for(var o=n.mainAxis,s=o===void 0?!0:o,a=n.altAxis,c=a===void 0?!0:a,d=n.fallbackPlacements,p=n.padding,h=n.boundary,m=n.rootBoundary,v=n.altBoundary,b=n.flipVariations,w=b===void 0?!0:b,y=n.allowedAutoPlacements,S=t.options.placement,k=ta(S),_=k===S,I=d||(_||!w?[yp(S)]:T$(S)),P=[S].concat(I).reduce(function(X,K){return X.concat(ta(K)===yb?D$(t,{placement:K,boundary:h,rootBoundary:m,padding:p,flipVariations:w,allowedAutoPlacements:y}):K)},[]),E=t.rects.reference,O=t.rects.popper,R=new Map,M=!0,T=P[0],A=0;A=0,q=V?"width":"height",G=Yu(t,{placement:$,boundary:h,rootBoundary:m,altBoundary:v,padding:p}),D=V?B?is:ko:B?as:Co;E[q]>O[q]&&(D=yp(D));var L=yp(D),W=[];if(s&&W.push(G[Q]<=0),c&&W.push(G[D]<=0,G[L]<=0),W.every(function(X){return X})){T=$,M=!1;break}R.set($,W)}if(M)for(var Y=w?3:1,ae=function(K){var U=P.find(function(se){var re=R.get(se);if(re)return re.slice(0,K).every(function(oe){return oe})});if(U)return T=U,"break"},ye=Y;ye>0;ye--){var ue=ae(ye);if(ue==="break")break}t.placement!==T&&(t.modifiersData[r]._skip=!0,t.placement=T,t.reset=!0)}}const N$={name:"flip",enabled:!0,phase:"main",fn:A$,requiresIfExists:["offset"],data:{_skip:!1}};function Gw(e,t,n){return n===void 0&&(n={x:0,y:0}),{top:e.top-t.height-n.y,right:e.right-t.width+n.x,bottom:e.bottom-t.height+n.y,left:e.left-t.width-n.x}}function qw(e){return[Co,is,as,ko].some(function(t){return e[t]>=0})}function $$(e){var t=e.state,n=e.name,r=t.rects.reference,o=t.rects.popper,s=t.modifiersData.preventOverflow,a=Yu(t,{elementContext:"reference"}),c=Yu(t,{altBoundary:!0}),d=Gw(a,r),p=Gw(c,o,s),h=qw(d),m=qw(p);t.modifiersData[n]={referenceClippingOffsets:d,popperEscapeOffsets:p,isReferenceHidden:h,hasPopperEscaped:m},t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-reference-hidden":h,"data-popper-escaped":m})}const z$={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:$$};function L$(e,t,n){var r=ta(e),o=[ko,Co].indexOf(r)>=0?-1:1,s=typeof n=="function"?n(Object.assign({},t,{placement:e})):n,a=s[0],c=s[1];return a=a||0,c=(c||0)*o,[ko,is].indexOf(r)>=0?{x:c,y:a}:{x:a,y:c}}function B$(e){var t=e.state,n=e.options,r=e.name,o=n.offset,s=o===void 0?[0,0]:o,a=KP.reduce(function(h,m){return h[m]=L$(m,t.rects,s),h},{}),c=a[t.placement],d=c.x,p=c.y;t.modifiersData.popperOffsets!=null&&(t.modifiersData.popperOffsets.x+=d,t.modifiersData.popperOffsets.y+=p),t.modifiersData[r]=a}const F$={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:B$};function H$(e){var t=e.state,n=e.name;t.modifiersData[n]=t5({reference:t.rects.reference,element:t.rects.popper,strategy:"absolute",placement:t.placement})}const W$={name:"popperOffsets",enabled:!0,phase:"read",fn:H$,data:{}};function V$(e){return e==="x"?"y":"x"}function U$(e){var t=e.state,n=e.options,r=e.name,o=n.mainAxis,s=o===void 0?!0:o,a=n.altAxis,c=a===void 0?!1:a,d=n.boundary,p=n.rootBoundary,h=n.altBoundary,m=n.padding,v=n.tether,b=v===void 0?!0:v,w=n.tetherOffset,y=w===void 0?0:w,S=Yu(t,{boundary:d,rootBoundary:p,padding:m,altBoundary:h}),k=ta(t.placement),_=xc(t.placement),I=!_,P=Sb(k),E=V$(P),O=t.modifiersData.popperOffsets,R=t.rects.reference,M=t.rects.popper,T=typeof y=="function"?y(Object.assign({},t.rects,{placement:t.placement})):y,A=typeof T=="number"?{mainAxis:T,altAxis:T}:Object.assign({mainAxis:0,altAxis:0},T),$=t.modifiersData.offset?t.modifiersData.offset[t.placement]:null,Q={x:0,y:0};if(O){if(s){var B,V=P==="y"?Co:ko,q=P==="y"?as:is,G=P==="y"?"height":"width",D=O[P],L=D+S[V],W=D-S[q],Y=b?-M[G]/2:0,ae=_===vc?R[G]:M[G],ye=_===vc?-M[G]:-R[G],ue=t.elements.arrow,X=b&&ue?wb(ue):{width:0,height:0},K=t.modifiersData["arrow#persistent"]?t.modifiersData["arrow#persistent"].padding:QP(),U=K[V],se=K[q],re=Tu(0,R[G],X[G]),oe=I?R[G]/2-Y-re-U-A.mainAxis:ae-re-U-A.mainAxis,pe=I?-R[G]/2+Y+re+se+A.mainAxis:ye+re+se+A.mainAxis,le=t.elements.arrow&&wd(t.elements.arrow),ge=le?P==="y"?le.clientTop||0:le.clientLeft||0:0,_e=(B=$==null?void 0:$[P])!=null?B:0,ie=D+oe-_e-ge,Se=D+pe-_e,Fe=Tu(b?Vp(L,ie):L,D,b?Xi(W,Se):W);O[P]=Fe,Q[P]=Fe-D}if(c){var Ae,He=P==="x"?Co:ko,Ct=P==="x"?as:is,ct=O[E],on=E==="y"?"height":"width",vt=ct+S[He],bt=ct-S[Ct],we=[Co,ko].indexOf(k)!==-1,Re=(Ae=$==null?void 0:$[E])!=null?Ae:0,Pt=we?vt:ct-R[on]-M[on]-Re+A.altAxis,At=we?ct+R[on]+M[on]-Re-A.altAxis:bt,xe=b&&we?m$(Pt,ct,At):Tu(b?Pt:vt,ct,b?At:bt);O[E]=xe,Q[E]=xe-ct}t.modifiersData[r]=Q}}const G$={name:"preventOverflow",enabled:!0,phase:"main",fn:U$,requiresIfExists:["offset"]};function q$(e){return{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}}function K$(e){return e===Lo(e)||!rs(e)?Cb(e):q$(e)}function Y$(e){var t=e.getBoundingClientRect(),n=bc(t.width)/e.offsetWidth||1,r=bc(t.height)/e.offsetHeight||1;return n!==1||r!==1}function X$(e,t,n){n===void 0&&(n=!1);var r=rs(t),o=rs(t)&&Y$(t),s=Pi(t),a=yc(e,o,n),c={scrollLeft:0,scrollTop:0},d={x:0,y:0};return(r||!r&&!n)&&((ra(t)!=="body"||_b(s))&&(c=K$(t)),rs(t)?(d=yc(t,!0),d.x+=t.clientLeft,d.y+=t.clientTop):s&&(d.x=kb(s))),{x:a.left+c.scrollLeft-d.x,y:a.top+c.scrollTop-d.y,width:a.width,height:a.height}}function Q$(e){var t=new Map,n=new Set,r=[];e.forEach(function(s){t.set(s.name,s)});function o(s){n.add(s.name);var a=[].concat(s.requires||[],s.requiresIfExists||[]);a.forEach(function(c){if(!n.has(c)){var d=t.get(c);d&&o(d)}}),r.push(s)}return e.forEach(function(s){n.has(s.name)||o(s)}),r}function J$(e){var t=Q$(e);return c$.reduce(function(n,r){return n.concat(t.filter(function(o){return o.phase===r}))},[])}function Z$(e){var t;return function(){return t||(t=new Promise(function(n){Promise.resolve().then(function(){t=void 0,n(e())})})),t}}function ez(e){var t=e.reduce(function(n,r){var o=n[r.name];return n[r.name]=o?Object.assign({},o,r,{options:Object.assign({},o.options,r.options),data:Object.assign({},o.data,r.data)}):r,n},{});return Object.keys(t).map(function(n){return t[n]})}var Kw={placement:"bottom",modifiers:[],strategy:"absolute"};function Yw(){for(var e=arguments.length,t=new Array(e),n=0;n{}),I=f.useCallback(()=>{var A;!t||!w.current||!y.current||((A=_.current)==null||A.call(_),S.current=rz(w.current,y.current,{placement:k,modifiers:[KN,UN,VN,{...WN,enabled:!!v},{name:"eventListeners",...HN(a)},{name:"arrow",options:{padding:s}},{name:"offset",options:{offset:c??[0,d]}},{name:"flip",enabled:!!p,options:{padding:8}},{name:"preventOverflow",enabled:!!m,options:{boundary:h}},...n??[]],strategy:o}),S.current.forceUpdate(),_.current=S.current.destroy)},[k,t,n,v,a,s,c,d,p,m,h,o]);f.useEffect(()=>()=>{var A;!w.current&&!y.current&&((A=S.current)==null||A.destroy(),S.current=null)},[]);const P=f.useCallback(A=>{w.current=A,I()},[I]),E=f.useCallback((A={},$=null)=>({...A,ref:cn(P,$)}),[P]),O=f.useCallback(A=>{y.current=A,I()},[I]),R=f.useCallback((A={},$=null)=>({...A,ref:cn(O,$),style:{...A.style,position:o,minWidth:v?void 0:"max-content",inset:"0 auto auto 0"}}),[o,O,v]),M=f.useCallback((A={},$=null)=>{const{size:Q,shadowColor:B,bg:V,style:q,...G}=A;return{...G,ref:$,"data-popper-arrow":"",style:oz(A)}},[]),T=f.useCallback((A={},$=null)=>({...A,ref:$,"data-popper-arrow-inner":""}),[]);return{update(){var A;(A=S.current)==null||A.update()},forceUpdate(){var A;(A=S.current)==null||A.forceUpdate()},transformOrigin:Pr.transformOrigin.varRef,referenceRef:P,popperRef:O,getPopperProps:R,getArrowProps:M,getArrowInnerProps:T,getReferenceProps:E}}function oz(e){const{size:t,shadowColor:n,bg:r,style:o}=e,s={...o,position:"absolute"};return t&&(s["--popper-arrow-size"]=t),n&&(s["--popper-arrow-shadow-color"]=n),r&&(s["--popper-arrow-bg"]=r),s}function jb(e={}){const{onClose:t,onOpen:n,isOpen:r,id:o}=e,s=rr(n),a=rr(t),[c,d]=f.useState(e.defaultIsOpen||!1),p=r!==void 0?r:c,h=r!==void 0,m=f.useId(),v=o??`disclosure-${m}`,b=f.useCallback(()=>{h||d(!1),a==null||a()},[h,a]),w=f.useCallback(()=>{h||d(!0),s==null||s()},[h,s]),y=f.useCallback(()=>{p?b():w()},[p,w,b]);function S(_={}){return{..._,"aria-expanded":p,"aria-controls":v,onClick(I){var P;(P=_.onClick)==null||P.call(_,I),y()}}}function k(_={}){return{..._,hidden:!p,id:v}}return{isOpen:p,onOpen:w,onClose:b,onToggle:y,isControlled:h,getButtonProps:S,getDisclosureProps:k}}function sz(e){const{ref:t,handler:n,enabled:r=!0}=e,o=rr(n),a=f.useRef({isPointerDown:!1,ignoreEmulatedMouseEvents:!1}).current;f.useEffect(()=>{if(!r)return;const c=m=>{y0(m,t)&&(a.isPointerDown=!0)},d=m=>{if(a.ignoreEmulatedMouseEvents){a.ignoreEmulatedMouseEvents=!1;return}a.isPointerDown&&n&&y0(m,t)&&(a.isPointerDown=!1,o(m))},p=m=>{a.ignoreEmulatedMouseEvents=!0,n&&a.isPointerDown&&y0(m,t)&&(a.isPointerDown=!1,o(m))},h=n5(t.current);return h.addEventListener("mousedown",c,!0),h.addEventListener("mouseup",d,!0),h.addEventListener("touchstart",c,!0),h.addEventListener("touchend",p,!0),()=>{h.removeEventListener("mousedown",c,!0),h.removeEventListener("mouseup",d,!0),h.removeEventListener("touchstart",c,!0),h.removeEventListener("touchend",p,!0)}},[n,t,o,a,r])}function y0(e,t){var n;const r=e.target;return r&&!n5(r).contains(r)?!1:!((n=t.current)!=null&&n.contains(r))}function n5(e){var t;return(t=e==null?void 0:e.ownerDocument)!=null?t:document}function r5(e){const{isOpen:t,ref:n}=e,[r,o]=f.useState(t),[s,a]=f.useState(!1);return f.useEffect(()=>{s||(o(t),a(!0))},[t,s,r]),Yi(()=>n.current,"animationend",()=>{o(t)}),{present:!(t?!1:!r),onComplete(){var d;const p=uN(n.current),h=new p.CustomEvent("animationend",{bubbles:!0});(d=n.current)==null||d.dispatchEvent(h)}}}function Ib(e){const{wasSelected:t,enabled:n,isSelected:r,mode:o="unmount"}=e;return!!(!n||r||o==="keepMounted"&&t)}var[az,iz,lz,cz]=X1(),[uz,Sd]=Rn({strict:!1,name:"MenuContext"});function dz(e,...t){const n=f.useId(),r=e||n;return f.useMemo(()=>t.map(o=>`${o}-${r}`),[r,t])}function o5(e){var t;return(t=e==null?void 0:e.ownerDocument)!=null?t:document}function Xw(e){return o5(e).activeElement===e}function fz(e={}){const{id:t,closeOnSelect:n=!0,closeOnBlur:r=!0,initialFocusRef:o,autoSelect:s=!0,isLazy:a,isOpen:c,defaultIsOpen:d,onClose:p,onOpen:h,placement:m="bottom-start",lazyBehavior:v="unmount",direction:b,computePositionOnMount:w=!1,...y}=e,S=f.useRef(null),k=f.useRef(null),_=lz(),I=f.useCallback(()=>{requestAnimationFrame(()=>{var ue;(ue=S.current)==null||ue.focus({preventScroll:!1})})},[]),P=f.useCallback(()=>{const ue=setTimeout(()=>{var X;if(o)(X=o.current)==null||X.focus();else{const K=_.firstEnabled();K&&B(K.index)}});L.current.add(ue)},[_,o]),E=f.useCallback(()=>{const ue=setTimeout(()=>{const X=_.lastEnabled();X&&B(X.index)});L.current.add(ue)},[_]),O=f.useCallback(()=>{h==null||h(),s?P():I()},[s,P,I,h]),{isOpen:R,onOpen:M,onClose:T,onToggle:A}=jb({isOpen:c,defaultIsOpen:d,onClose:p,onOpen:O});sz({enabled:R&&r,ref:S,handler:ue=>{var X;(X=k.current)!=null&&X.contains(ue.target)||T()}});const $=Pb({...y,enabled:R||w,placement:m,direction:b}),[Q,B]=f.useState(-1);Ba(()=>{R||B(-1)},[R]),GP(S,{focusRef:k,visible:R,shouldFocus:!0});const V=r5({isOpen:R,ref:S}),[q,G]=dz(t,"menu-button","menu-list"),D=f.useCallback(()=>{M(),I()},[M,I]),L=f.useRef(new Set([]));xz(()=>{L.current.forEach(ue=>clearTimeout(ue)),L.current.clear()});const W=f.useCallback(()=>{M(),P()},[P,M]),Y=f.useCallback(()=>{M(),E()},[M,E]),ae=f.useCallback(()=>{var ue,X;const K=o5(S.current),U=(ue=S.current)==null?void 0:ue.contains(K.activeElement);if(!(R&&!U))return;const re=(X=_.item(Q))==null?void 0:X.node;re==null||re.focus()},[R,Q,_]),ye=f.useRef(null);return{openAndFocusMenu:D,openAndFocusFirstItem:W,openAndFocusLastItem:Y,onTransitionEnd:ae,unstable__animationState:V,descendants:_,popper:$,buttonId:q,menuId:G,forceUpdate:$.forceUpdate,orientation:"vertical",isOpen:R,onToggle:A,onOpen:M,onClose:T,menuRef:S,buttonRef:k,focusedIndex:Q,closeOnSelect:n,closeOnBlur:r,autoSelect:s,setFocusedIndex:B,isLazy:a,lazyBehavior:v,initialFocusRef:o,rafId:ye}}function pz(e={},t=null){const n=Sd(),{onToggle:r,popper:o,openAndFocusFirstItem:s,openAndFocusLastItem:a}=n,c=f.useCallback(d=>{const p=d.key,m={Enter:s,ArrowDown:s,ArrowUp:a}[p];m&&(d.preventDefault(),d.stopPropagation(),m(d))},[s,a]);return{...e,ref:cn(n.buttonRef,t,o.referenceRef),id:n.buttonId,"data-active":tn(n.isOpen),"aria-expanded":n.isOpen,"aria-haspopup":"menu","aria-controls":n.menuId,onClick:et(e.onClick,r),onKeyDown:et(e.onKeyDown,c)}}function $v(e){var t;return bz(e)&&!!((t=e==null?void 0:e.getAttribute("role"))!=null&&t.startsWith("menuitem"))}function hz(e={},t=null){const n=Sd();if(!n)throw new Error("useMenuContext: context is undefined. Seems you forgot to wrap component within

");const{focusedIndex:r,setFocusedIndex:o,menuRef:s,isOpen:a,onClose:c,menuId:d,isLazy:p,lazyBehavior:h,unstable__animationState:m}=n,v=iz(),b=MN({preventDefault:k=>k.key!==" "&&$v(k.target)}),w=f.useCallback(k=>{if(!k.currentTarget.contains(k.target))return;const _=k.key,P={Tab:O=>O.preventDefault(),Escape:c,ArrowDown:()=>{const O=v.nextEnabled(r);O&&o(O.index)},ArrowUp:()=>{const O=v.prevEnabled(r);O&&o(O.index)}}[_];if(P){k.preventDefault(),P(k);return}const E=b(O=>{const R=DN(v.values(),O,M=>{var T,A;return(A=(T=M==null?void 0:M.node)==null?void 0:T.textContent)!=null?A:""},v.item(r));if(R){const M=v.indexOf(R.node);o(M)}});$v(k.target)&&E(k)},[v,r,b,c,o]),y=f.useRef(!1);a&&(y.current=!0);const S=Ib({wasSelected:y.current,enabled:p,mode:h,isSelected:m.present});return{...e,ref:cn(s,t),children:S?e.children:null,tabIndex:-1,role:"menu",id:d,style:{...e.style,transformOrigin:"var(--popper-transform-origin)"},"aria-orientation":"vertical",onKeyDown:et(e.onKeyDown,w)}}function mz(e={}){const{popper:t,isOpen:n}=Sd();return t.getPopperProps({...e,style:{visibility:n?"visible":"hidden",...e.style}})}function s5(e={},t=null){const{onMouseEnter:n,onMouseMove:r,onMouseLeave:o,onClick:s,onFocus:a,isDisabled:c,isFocusable:d,closeOnSelect:p,type:h,...m}=e,v=Sd(),{setFocusedIndex:b,focusedIndex:w,closeOnSelect:y,onClose:S,menuRef:k,isOpen:_,menuId:I,rafId:P}=v,E=f.useRef(null),O=`${I}-menuitem-${f.useId()}`,{index:R,register:M}=cz({disabled:c&&!d}),T=f.useCallback(D=>{n==null||n(D),!c&&b(R)},[b,R,c,n]),A=f.useCallback(D=>{r==null||r(D),E.current&&!Xw(E.current)&&T(D)},[T,r]),$=f.useCallback(D=>{o==null||o(D),!c&&b(-1)},[b,c,o]),Q=f.useCallback(D=>{s==null||s(D),$v(D.currentTarget)&&(p??y)&&S()},[S,s,y,p]),B=f.useCallback(D=>{a==null||a(D),b(R)},[b,a,R]),V=R===w,q=c&&!d;Ba(()=>{_&&(V&&!q&&E.current?(P.current&&cancelAnimationFrame(P.current),P.current=requestAnimationFrame(()=>{var D;(D=E.current)==null||D.focus(),P.current=null})):k.current&&!Xw(k.current)&&k.current.focus({preventScroll:!0}))},[V,q,k,_]);const G=UP({onClick:Q,onFocus:B,onMouseEnter:T,onMouseMove:A,onMouseLeave:$,ref:cn(M,E,t),isDisabled:c,isFocusable:d});return{...m,...G,type:h??G.type,id:O,role:"menuitem",tabIndex:V?0:-1}}function gz(e={},t=null){const{type:n="radio",isChecked:r,...o}=e;return{...s5(o,t),role:`menuitem${n}`,"aria-checked":r}}function vz(e={}){const{children:t,type:n="radio",value:r,defaultValue:o,onChange:s,...a}=e,d=n==="radio"?"":[],[p,h]=Ac({defaultValue:o??d,value:r,onChange:s}),m=f.useCallback(w=>{if(n==="radio"&&typeof p=="string"&&h(w),n==="checkbox"&&Array.isArray(p)){const y=p.includes(w)?p.filter(S=>S!==w):p.concat(w);h(y)}},[p,h,n]),b=gd(t).map(w=>{if(w.type.id!=="MenuItemOption")return w;const y=k=>{var _,I;m(w.props.value),(I=(_=w.props).onClick)==null||I.call(_,k)},S=n==="radio"?w.props.value===p:p.includes(w.props.value);return f.cloneElement(w,{type:n,onClick:y,isChecked:S})});return{...a,children:b}}function bz(e){var t;if(!yz(e))return!1;const n=(t=e.ownerDocument.defaultView)!=null?t:window;return e instanceof n.HTMLElement}function yz(e){return e!=null&&typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.ELEMENT_NODE}function xz(e,t=[]){return f.useEffect(()=>()=>e(),t)}var[wz,Cd]=Rn({name:"MenuStylesContext",errorMessage:`useMenuStyles returned is 'undefined'. Seems you forgot to wrap the components in "" `}),kd=e=>{const{children:t}=e,n=Br("Menu",e),r=qn(e),{direction:o}=Mc(),{descendants:s,...a}=fz({...r,direction:o}),c=f.useMemo(()=>a,[a]),{isOpen:d,onClose:p,forceUpdate:h}=c;return i.jsx(az,{value:s,children:i.jsx(uz,{value:c,children:i.jsx(wz,{value:n,children:D1(t,{isOpen:d,onClose:p,forceUpdate:h})})})})};kd.displayName="Menu";var a5=Te((e,t)=>{const n=Cd();return i.jsx(Ie.span,{ref:t,...e,__css:n.command,className:"chakra-menu__command"})});a5.displayName="MenuCommand";var i5=Te((e,t)=>{const{type:n,...r}=e,o=Cd(),s=r.as||n?n??void 0:"button",a=f.useMemo(()=>({textDecoration:"none",color:"inherit",userSelect:"none",display:"flex",width:"100%",alignItems:"center",textAlign:"start",flex:"0 0 auto",outline:0,...o.item}),[o.item]);return i.jsx(Ie.button,{ref:t,type:s,...r,__css:a})}),Eb=e=>{const{className:t,children:n,...r}=e,o=f.Children.only(n),s=f.isValidElement(o)?f.cloneElement(o,{focusable:"false","aria-hidden":!0,className:kt("chakra-menu__icon",o.props.className)}):null,a=kt("chakra-menu__icon-wrapper",t);return i.jsx(Ie.span,{className:a,...r,__css:{display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:s})};Eb.displayName="MenuIcon";var _r=Te((e,t)=>{const{icon:n,iconSpacing:r="0.75rem",command:o,commandSpacing:s="0.75rem",children:a,...c}=e,d=s5(c,t),h=n||o?i.jsx("span",{style:{pointerEvents:"none",flex:1},children:a}):a;return i.jsxs(i5,{...d,className:kt("chakra-menu__menuitem",d.className),children:[n&&i.jsx(Eb,{fontSize:"0.8em",marginEnd:r,children:n}),h,o&&i.jsx(a5,{marginStart:s,children:o})]})});_r.displayName="MenuItem";var Sz={enter:{visibility:"visible",opacity:1,scale:1,transition:{duration:.2,ease:[.4,0,.2,1]}},exit:{transitionEnd:{visibility:"hidden"},opacity:0,scale:.8,transition:{duration:.1,easings:"easeOut"}}},Cz=Ie(Xr.div),zc=Te(function(t,n){var r,o;const{rootProps:s,motionProps:a,...c}=t,{isOpen:d,onTransitionEnd:p,unstable__animationState:h}=Sd(),m=hz(c,n),v=mz(s),b=Cd();return i.jsx(Ie.div,{...v,__css:{zIndex:(o=t.zIndex)!=null?o:(r=b.list)==null?void 0:r.zIndex},children:i.jsx(Cz,{variants:Sz,initial:!1,animate:d?"enter":"exit",__css:{outline:0,...b.list},...a,className:kt("chakra-menu__menu-list",m.className),...m,onUpdate:p,onAnimationComplete:Jh(h.onComplete,m.onAnimationComplete)})})});zc.displayName="MenuList";var Xu=Te((e,t)=>{const{title:n,children:r,className:o,...s}=e,a=kt("chakra-menu__group__title",o),c=Cd();return i.jsxs("div",{ref:t,className:"chakra-menu__group",role:"group",children:[n&&i.jsx(Ie.p,{className:a,...s,__css:c.groupTitle,children:n}),r]})});Xu.displayName="MenuGroup";var l5=e=>{const{className:t,title:n,...r}=e,o=vz(r);return i.jsx(Xu,{title:n,className:kt("chakra-menu__option-group",t),...o})};l5.displayName="MenuOptionGroup";var kz=Te((e,t)=>{const n=Cd();return i.jsx(Ie.button,{ref:t,...e,__css:{display:"inline-flex",appearance:"none",alignItems:"center",outline:0,...n.button}})}),_d=Te((e,t)=>{const{children:n,as:r,...o}=e,s=pz(o,t),a=r||kz;return i.jsx(a,{...s,className:kt("chakra-menu__menu-button",e.className),children:i.jsx(Ie.span,{__css:{pointerEvents:"none",flex:"1 1 auto",minW:0},children:e.children})})});_d.displayName="MenuButton";var _z=e=>i.jsx("svg",{viewBox:"0 0 14 14",width:"1em",height:"1em",...e,children:i.jsx("polygon",{fill:"currentColor",points:"5.5 11.9993304 14 3.49933039 12.5 2 5.5 8.99933039 1.5 4.9968652 0 6.49933039"})}),Up=Te((e,t)=>{const{icon:n,iconSpacing:r="0.75rem",...o}=e,s=gz(o,t);return i.jsxs(i5,{...s,className:kt("chakra-menu__menuitem-option",o.className),children:[n!==null&&i.jsx(Eb,{fontSize:"0.8em",marginEnd:r,opacity:e.isChecked?1:0,children:n||i.jsx(_z,{})}),i.jsx("span",{style:{flex:1},children:s.children})]})});Up.id="MenuItemOption";Up.displayName="MenuItemOption";var Pz={slideInBottom:{...Cv,custom:{offsetY:16,reverse:!0}},slideInRight:{...Cv,custom:{offsetX:16,reverse:!0}},scale:{...T3,custom:{initialScale:.95,reverse:!0}},none:{}},jz=Ie(Xr.section),Iz=e=>Pz[e||"none"],c5=f.forwardRef((e,t)=>{const{preset:n,motionProps:r=Iz(n),...o}=e;return i.jsx(jz,{ref:t,...r,...o})});c5.displayName="ModalTransition";var Ez=Object.defineProperty,Oz=(e,t,n)=>t in e?Ez(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Rz=(e,t,n)=>(Oz(e,typeof t!="symbol"?t+"":t,n),n),Mz=class{constructor(){Rz(this,"modals"),this.modals=new Map}add(e){return this.modals.set(e,this.modals.size+1),this.modals.size}remove(e){this.modals.delete(e)}isTopModal(e){return e?this.modals.get(e)===this.modals.size:!1}},zv=new Mz;function u5(e,t){const[n,r]=f.useState(0);return f.useEffect(()=>{const o=e.current;if(o){if(t){const s=zv.add(o);r(s)}return()=>{zv.remove(o),r(0)}}},[t,e]),n}var Dz=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Al=new WeakMap,Df=new WeakMap,Tf={},x0=0,d5=function(e){return e&&(e.host||d5(e.parentNode))},Tz=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=d5(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},Az=function(e,t,n,r){var o=Tz(t,Array.isArray(e)?e:[e]);Tf[n]||(Tf[n]=new WeakMap);var s=Tf[n],a=[],c=new Set,d=new Set(o),p=function(m){!m||c.has(m)||(c.add(m),p(m.parentNode))};o.forEach(p);var h=function(m){!m||d.has(m)||Array.prototype.forEach.call(m.children,function(v){if(c.has(v))h(v);else{var b=v.getAttribute(r),w=b!==null&&b!=="false",y=(Al.get(v)||0)+1,S=(s.get(v)||0)+1;Al.set(v,y),s.set(v,S),a.push(v),y===1&&w&&Df.set(v,!0),S===1&&v.setAttribute(n,"true"),w||v.setAttribute(r,"true")}})};return h(t),c.clear(),x0++,function(){a.forEach(function(m){var v=Al.get(m)-1,b=s.get(m)-1;Al.set(m,v),s.set(m,b),v||(Df.has(m)||m.removeAttribute(r),Df.delete(m)),b||m.removeAttribute(n)}),x0--,x0||(Al=new WeakMap,Al=new WeakMap,Df=new WeakMap,Tf={})}},Nz=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||Dz(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),Az(r,o,n,"aria-hidden")):function(){return null}};function $z(e){const{isOpen:t,onClose:n,id:r,closeOnOverlayClick:o=!0,closeOnEsc:s=!0,useInert:a=!0,onOverlayClick:c,onEsc:d}=e,p=f.useRef(null),h=f.useRef(null),[m,v,b]=Lz(r,"chakra-modal","chakra-modal--header","chakra-modal--body");zz(p,t&&a);const w=u5(p,t),y=f.useRef(null),S=f.useCallback(T=>{y.current=T.target},[]),k=f.useCallback(T=>{T.key==="Escape"&&(T.stopPropagation(),s&&(n==null||n()),d==null||d())},[s,n,d]),[_,I]=f.useState(!1),[P,E]=f.useState(!1),O=f.useCallback((T={},A=null)=>({role:"dialog",...T,ref:cn(A,p),id:m,tabIndex:-1,"aria-modal":!0,"aria-labelledby":_?v:void 0,"aria-describedby":P?b:void 0,onClick:et(T.onClick,$=>$.stopPropagation())}),[b,P,m,v,_]),R=f.useCallback(T=>{T.stopPropagation(),y.current===T.target&&zv.isTopModal(p.current)&&(o&&(n==null||n()),c==null||c())},[n,o,c]),M=f.useCallback((T={},A=null)=>({...T,ref:cn(A,h),onClick:et(T.onClick,R),onKeyDown:et(T.onKeyDown,k),onMouseDown:et(T.onMouseDown,S)}),[k,S,R]);return{isOpen:t,onClose:n,headerId:v,bodyId:b,setBodyMounted:E,setHeaderMounted:I,dialogRef:p,overlayRef:h,getDialogProps:O,getDialogContainerProps:M,index:w}}function zz(e,t){const n=e.current;f.useEffect(()=>{if(!(!e.current||!t))return Nz(e.current)},[t,e,n])}function Lz(e,...t){const n=f.useId(),r=e||n;return f.useMemo(()=>t.map(o=>`${o}-${r}`),[r,t])}var[Bz,Lc]=Rn({name:"ModalStylesContext",errorMessage:`useModalStyles returned is 'undefined'. Seems you forgot to wrap the components in "" `}),[Fz,sl]=Rn({strict:!0,name:"ModalContext",errorMessage:"useModalContext: `context` is undefined. Seems you forgot to wrap modal components in ``"}),Qu=e=>{const t={scrollBehavior:"outside",autoFocus:!0,trapFocus:!0,returnFocusOnClose:!0,blockScrollOnMount:!0,allowPinchZoom:!1,motionPreset:"scale",lockFocusAcrossFrames:!0,...e},{portalProps:n,children:r,autoFocus:o,trapFocus:s,initialFocusRef:a,finalFocusRef:c,returnFocusOnClose:d,blockScrollOnMount:p,allowPinchZoom:h,preserveScrollBarGap:m,motionPreset:v,lockFocusAcrossFrames:b,onCloseComplete:w}=t,y=Br("Modal",t),k={...$z(t),autoFocus:o,trapFocus:s,initialFocusRef:a,finalFocusRef:c,returnFocusOnClose:d,blockScrollOnMount:p,allowPinchZoom:h,preserveScrollBarGap:m,motionPreset:v,lockFocusAcrossFrames:b};return i.jsx(Fz,{value:k,children:i.jsx(Bz,{value:y,children:i.jsx(Fo,{onExitComplete:w,children:k.isOpen&&i.jsx(Vu,{...n,children:r})})})})};Qu.displayName="Modal";var xp="right-scroll-bar-position",wp="width-before-scroll-bar",Hz="with-scroll-bars-hidden",Wz="--removed-body-scroll-bar-size",f5=iP(),w0=function(){},cm=f.forwardRef(function(e,t){var n=f.useRef(null),r=f.useState({onScrollCapture:w0,onWheelCapture:w0,onTouchMoveCapture:w0}),o=r[0],s=r[1],a=e.forwardProps,c=e.children,d=e.className,p=e.removeScrollBar,h=e.enabled,m=e.shards,v=e.sideCar,b=e.noIsolation,w=e.inert,y=e.allowPinchZoom,S=e.as,k=S===void 0?"div":S,_=e.gapMode,I=oP(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noIsolation","inert","allowPinchZoom","as","gapMode"]),P=v,E=rP([n,t]),O=Qs(Qs({},I),o);return f.createElement(f.Fragment,null,h&&f.createElement(P,{sideCar:f5,removeScrollBar:p,shards:m,noIsolation:b,inert:w,setCallbacks:s,allowPinchZoom:!!y,lockRef:n,gapMode:_}),a?f.cloneElement(f.Children.only(c),Qs(Qs({},O),{ref:E})):f.createElement(k,Qs({},O,{className:d,ref:E}),c))});cm.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};cm.classNames={fullWidth:wp,zeroRight:xp};var Qw,Vz=function(){if(Qw)return Qw;if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Uz(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Vz();return t&&e.setAttribute("nonce",t),e}function Gz(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function qz(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Kz=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Uz())&&(Gz(t,n),qz(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Yz=function(){var e=Kz();return function(t,n){f.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},p5=function(){var e=Yz(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Xz={left:0,top:0,right:0,gap:0},S0=function(e){return parseInt(e||"",10)||0},Qz=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[S0(n),S0(r),S0(o)]},Jz=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Xz;var t=Qz(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Zz=p5(),eL=function(e,t,n,r){var o=e.left,s=e.top,a=e.right,c=e.gap;return n===void 0&&(n="margin"),` + .`.concat(Hz,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(c,"px ").concat(r,`; + } + body { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&` + padding-left: `.concat(o,`px; + padding-top: `).concat(s,`px; + padding-right: `).concat(a,`px; + margin-left:0; + margin-top:0; + margin-right: `).concat(c,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(c,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(xp,` { + right: `).concat(c,"px ").concat(r,`; + } + + .`).concat(wp,` { + margin-right: `).concat(c,"px ").concat(r,`; + } + + .`).concat(xp," .").concat(xp,` { + right: 0 `).concat(r,`; + } + + .`).concat(wp," .").concat(wp,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(Wz,": ").concat(c,`px; + } +`)},tL=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,s=f.useMemo(function(){return Jz(o)},[o]);return f.createElement(Zz,{styles:eL(s,!t,o,n?"":"!important")})},Lv=!1;if(typeof window<"u")try{var Af=Object.defineProperty({},"passive",{get:function(){return Lv=!0,!0}});window.addEventListener("test",Af,Af),window.removeEventListener("test",Af,Af)}catch{Lv=!1}var Nl=Lv?{passive:!1}:!1,nL=function(e){return e.tagName==="TEXTAREA"},h5=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!nL(e)&&n[t]==="visible")},rL=function(e){return h5(e,"overflowY")},oL=function(e){return h5(e,"overflowX")},Jw=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=m5(e,r);if(o){var s=g5(e,r),a=s[1],c=s[2];if(a>c)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},sL=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},aL=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},m5=function(e,t){return e==="v"?rL(t):oL(t)},g5=function(e,t){return e==="v"?sL(t):aL(t)},iL=function(e,t){return e==="h"&&t==="rtl"?-1:1},lL=function(e,t,n,r,o){var s=iL(e,window.getComputedStyle(t).direction),a=s*r,c=n.target,d=t.contains(c),p=!1,h=a>0,m=0,v=0;do{var b=g5(e,c),w=b[0],y=b[1],S=b[2],k=y-S-s*w;(w||k)&&m5(e,c)&&(m+=k,v+=w),c=c.parentNode}while(!d&&c!==document.body||d&&(t.contains(c)||t===c));return(h&&(o&&m===0||!o&&a>m)||!h&&(o&&v===0||!o&&-a>v))&&(p=!0),p},Nf=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Zw=function(e){return[e.deltaX,e.deltaY]},eS=function(e){return e&&"current"in e?e.current:e},cL=function(e,t){return e[0]===t[0]&&e[1]===t[1]},uL=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},dL=0,$l=[];function fL(e){var t=f.useRef([]),n=f.useRef([0,0]),r=f.useRef(),o=f.useState(dL++)[0],s=f.useState(p5)[0],a=f.useRef(e);f.useEffect(function(){a.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var y=Ov([e.lockRef.current],(e.shards||[]).map(eS),!0).filter(Boolean);return y.forEach(function(S){return S.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),y.forEach(function(S){return S.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var c=f.useCallback(function(y,S){if("touches"in y&&y.touches.length===2)return!a.current.allowPinchZoom;var k=Nf(y),_=n.current,I="deltaX"in y?y.deltaX:_[0]-k[0],P="deltaY"in y?y.deltaY:_[1]-k[1],E,O=y.target,R=Math.abs(I)>Math.abs(P)?"h":"v";if("touches"in y&&R==="h"&&O.type==="range")return!1;var M=Jw(R,O);if(!M)return!0;if(M?E=R:(E=R==="v"?"h":"v",M=Jw(R,O)),!M)return!1;if(!r.current&&"changedTouches"in y&&(I||P)&&(r.current=E),!E)return!0;var T=r.current||E;return lL(T,S,y,T==="h"?I:P,!0)},[]),d=f.useCallback(function(y){var S=y;if(!(!$l.length||$l[$l.length-1]!==s)){var k="deltaY"in S?Zw(S):Nf(S),_=t.current.filter(function(E){return E.name===S.type&&E.target===S.target&&cL(E.delta,k)})[0];if(_&&_.should){S.cancelable&&S.preventDefault();return}if(!_){var I=(a.current.shards||[]).map(eS).filter(Boolean).filter(function(E){return E.contains(S.target)}),P=I.length>0?c(S,I[0]):!a.current.noIsolation;P&&S.cancelable&&S.preventDefault()}}},[]),p=f.useCallback(function(y,S,k,_){var I={name:y,delta:S,target:k,should:_};t.current.push(I),setTimeout(function(){t.current=t.current.filter(function(P){return P!==I})},1)},[]),h=f.useCallback(function(y){n.current=Nf(y),r.current=void 0},[]),m=f.useCallback(function(y){p(y.type,Zw(y),y.target,c(y,e.lockRef.current))},[]),v=f.useCallback(function(y){p(y.type,Nf(y),y.target,c(y,e.lockRef.current))},[]);f.useEffect(function(){return $l.push(s),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:v}),document.addEventListener("wheel",d,Nl),document.addEventListener("touchmove",d,Nl),document.addEventListener("touchstart",h,Nl),function(){$l=$l.filter(function(y){return y!==s}),document.removeEventListener("wheel",d,Nl),document.removeEventListener("touchmove",d,Nl),document.removeEventListener("touchstart",h,Nl)}},[]);var b=e.removeScrollBar,w=e.inert;return f.createElement(f.Fragment,null,w?f.createElement(s,{styles:uL(o)}):null,b?f.createElement(tL,{gapMode:e.gapMode}):null)}const pL=p9(f5,fL);var v5=f.forwardRef(function(e,t){return f.createElement(cm,Qs({},e,{ref:t,sideCar:pL}))});v5.classNames=cm.classNames;const hL=v5;function mL(e){const{autoFocus:t,trapFocus:n,dialogRef:r,initialFocusRef:o,blockScrollOnMount:s,allowPinchZoom:a,finalFocusRef:c,returnFocusOnClose:d,preserveScrollBarGap:p,lockFocusAcrossFrames:h,isOpen:m}=sl(),[v,b]=SR();f.useEffect(()=>{!v&&b&&setTimeout(b)},[v,b]);const w=u5(r,m);return i.jsx(zP,{autoFocus:t,isDisabled:!n,initialFocusRef:o,finalFocusRef:c,restoreFocus:d,contentRef:r,lockFocusAcrossFrames:h,children:i.jsx(hL,{removeScrollBar:!p,allowPinchZoom:a,enabled:w===1&&s,forwardProps:!0,children:e.children})})}var Ju=Te((e,t)=>{const{className:n,children:r,containerProps:o,motionProps:s,...a}=e,{getDialogProps:c,getDialogContainerProps:d}=sl(),p=c(a,t),h=d(o),m=kt("chakra-modal__content",n),v=Lc(),b={display:"flex",flexDirection:"column",position:"relative",width:"100%",outline:0,...v.dialog},w={display:"flex",width:"100vw",height:"$100vh",position:"fixed",left:0,top:0,...v.dialogContainer},{motionPreset:y}=sl();return i.jsx(mL,{children:i.jsx(Ie.div,{...h,className:"chakra-modal__content-container",tabIndex:-1,__css:w,children:i.jsx(c5,{preset:y,motionProps:s,className:m,...p,__css:b,children:r})})})});Ju.displayName="ModalContent";function Pd(e){const{leastDestructiveRef:t,...n}=e;return i.jsx(Qu,{...n,initialFocusRef:t})}var jd=Te((e,t)=>i.jsx(Ju,{ref:t,role:"alertdialog",...e})),Oa=Te((e,t)=>{const{className:n,...r}=e,o=kt("chakra-modal__footer",n),a={display:"flex",alignItems:"center",justifyContent:"flex-end",...Lc().footer};return i.jsx(Ie.footer,{ref:t,...r,__css:a,className:o})});Oa.displayName="ModalFooter";var Ra=Te((e,t)=>{const{className:n,...r}=e,{headerId:o,setHeaderMounted:s}=sl();f.useEffect(()=>(s(!0),()=>s(!1)),[s]);const a=kt("chakra-modal__header",n),d={flex:0,...Lc().header};return i.jsx(Ie.header,{ref:t,className:a,id:o,...r,__css:d})});Ra.displayName="ModalHeader";var gL=Ie(Xr.div),Ma=Te((e,t)=>{const{className:n,transition:r,motionProps:o,...s}=e,a=kt("chakra-modal__overlay",n),d={pos:"fixed",left:"0",top:"0",w:"100vw",h:"100vh",...Lc().overlay},{motionPreset:p}=sl(),m=o||(p==="none"?{}:D3);return i.jsx(gL,{...m,__css:d,ref:t,className:a,...s})});Ma.displayName="ModalOverlay";var Da=Te((e,t)=>{const{className:n,...r}=e,{bodyId:o,setBodyMounted:s}=sl();f.useEffect(()=>(s(!0),()=>s(!1)),[s]);const a=kt("chakra-modal__body",n),c=Lc();return i.jsx(Ie.div,{ref:t,className:a,id:o,...r,__css:c.body})});Da.displayName="ModalBody";var Ob=Te((e,t)=>{const{onClick:n,className:r,...o}=e,{onClose:s}=sl(),a=kt("chakra-modal__close-btn",r),c=Lc();return i.jsx(ND,{ref:t,__css:c.closeButton,className:a,onClick:et(n,d=>{d.stopPropagation(),s()}),...o})});Ob.displayName="ModalCloseButton";var vL=e=>i.jsx(Kr,{viewBox:"0 0 24 24",...e,children:i.jsx("path",{fill:"currentColor",d:"M21,5H3C2.621,5,2.275,5.214,2.105,5.553C1.937,5.892,1.973,6.297,2.2,6.6l9,12 c0.188,0.252,0.485,0.4,0.8,0.4s0.611-0.148,0.8-0.4l9-12c0.228-0.303,0.264-0.708,0.095-1.047C21.725,5.214,21.379,5,21,5z"})}),bL=e=>i.jsx(Kr,{viewBox:"0 0 24 24",...e,children:i.jsx("path",{fill:"currentColor",d:"M12.8,5.4c-0.377-0.504-1.223-0.504-1.6,0l-9,12c-0.228,0.303-0.264,0.708-0.095,1.047 C2.275,18.786,2.621,19,3,19h18c0.379,0,0.725-0.214,0.895-0.553c0.169-0.339,0.133-0.744-0.095-1.047L12.8,5.4z"})});function tS(e,t,n,r){f.useEffect(()=>{var o;if(!e.current||!r)return;const s=(o=e.current.ownerDocument.defaultView)!=null?o:window,a=Array.isArray(t)?t:[t],c=new s.MutationObserver(d=>{for(const p of d)p.type==="attributes"&&p.attributeName&&a.includes(p.attributeName)&&n(p)});return c.observe(e.current,{attributes:!0,attributeFilter:a}),()=>c.disconnect()})}function yL(e,t){const n=rr(e);f.useEffect(()=>{let r=null;const o=()=>n();return t!==null&&(r=window.setInterval(o,t)),()=>{r&&window.clearInterval(r)}},[t,n])}var xL=50,nS=300;function wL(e,t){const[n,r]=f.useState(!1),[o,s]=f.useState(null),[a,c]=f.useState(!0),d=f.useRef(null),p=()=>clearTimeout(d.current);yL(()=>{o==="increment"&&e(),o==="decrement"&&t()},n?xL:null);const h=f.useCallback(()=>{a&&e(),d.current=setTimeout(()=>{c(!1),r(!0),s("increment")},nS)},[e,a]),m=f.useCallback(()=>{a&&t(),d.current=setTimeout(()=>{c(!1),r(!0),s("decrement")},nS)},[t,a]),v=f.useCallback(()=>{c(!0),r(!1),p()},[]);return f.useEffect(()=>()=>p(),[]),{up:h,down:m,stop:v,isSpinning:n}}var SL=/^[Ee0-9+\-.]$/;function CL(e){return SL.test(e)}function kL(e,t){if(e.key==null)return!0;const n=e.ctrlKey||e.altKey||e.metaKey;return!(e.key.length===1)||n?!0:t(e.key)}function _L(e={}){const{focusInputOnChange:t=!0,clampValueOnBlur:n=!0,keepWithinRange:r=!0,min:o=Number.MIN_SAFE_INTEGER,max:s=Number.MAX_SAFE_INTEGER,step:a=1,isReadOnly:c,isDisabled:d,isRequired:p,isInvalid:h,pattern:m="[0-9]*(.[0-9]+)?",inputMode:v="decimal",allowMouseWheel:b,id:w,onChange:y,precision:S,name:k,"aria-describedby":_,"aria-label":I,"aria-labelledby":P,onFocus:E,onBlur:O,onInvalid:R,getAriaValueText:M,isValidCharacter:T,format:A,parse:$,...Q}=e,B=rr(E),V=rr(O),q=rr(R),G=rr(T??CL),D=rr(M),L=qA(e),{update:W,increment:Y,decrement:ae}=L,[ye,ue]=f.useState(!1),X=!(c||d),K=f.useRef(null),U=f.useRef(null),se=f.useRef(null),re=f.useRef(null),oe=f.useCallback(xe=>xe.split("").filter(G).join(""),[G]),pe=f.useCallback(xe=>{var ht;return(ht=$==null?void 0:$(xe))!=null?ht:xe},[$]),le=f.useCallback(xe=>{var ht;return((ht=A==null?void 0:A(xe))!=null?ht:xe).toString()},[A]);Ba(()=>{(L.valueAsNumber>s||L.valueAsNumber{if(!K.current)return;if(K.current.value!=L.value){const ht=pe(K.current.value);L.setValue(oe(ht))}},[pe,oe]);const ge=f.useCallback((xe=a)=>{X&&Y(xe)},[Y,X,a]),_e=f.useCallback((xe=a)=>{X&&ae(xe)},[ae,X,a]),ie=wL(ge,_e);tS(se,"disabled",ie.stop,ie.isSpinning),tS(re,"disabled",ie.stop,ie.isSpinning);const Se=f.useCallback(xe=>{if(xe.nativeEvent.isComposing)return;const $t=pe(xe.currentTarget.value);W(oe($t)),U.current={start:xe.currentTarget.selectionStart,end:xe.currentTarget.selectionEnd}},[W,oe,pe]),Fe=f.useCallback(xe=>{var ht,$t,zt;B==null||B(xe),U.current&&(xe.target.selectionStart=($t=U.current.start)!=null?$t:(ht=xe.currentTarget.value)==null?void 0:ht.length,xe.currentTarget.selectionEnd=(zt=U.current.end)!=null?zt:xe.currentTarget.selectionStart)},[B]),Ae=f.useCallback(xe=>{if(xe.nativeEvent.isComposing)return;kL(xe,G)||xe.preventDefault();const ht=He(xe)*a,$t=xe.key,Ne={ArrowUp:()=>ge(ht),ArrowDown:()=>_e(ht),Home:()=>W(o),End:()=>W(s)}[$t];Ne&&(xe.preventDefault(),Ne(xe))},[G,a,ge,_e,W,o,s]),He=xe=>{let ht=1;return(xe.metaKey||xe.ctrlKey)&&(ht=.1),xe.shiftKey&&(ht=10),ht},Ct=f.useMemo(()=>{const xe=D==null?void 0:D(L.value);if(xe!=null)return xe;const ht=L.value.toString();return ht||void 0},[L.value,D]),ct=f.useCallback(()=>{let xe=L.value;if(L.value==="")return;/^[eE]/.test(L.value.toString())?L.setValue(""):(L.valueAsNumbers&&(xe=s),L.cast(xe))},[L,s,o]),on=f.useCallback(()=>{ue(!1),n&&ct()},[n,ue,ct]),vt=f.useCallback(()=>{t&&requestAnimationFrame(()=>{var xe;(xe=K.current)==null||xe.focus()})},[t]),bt=f.useCallback(xe=>{xe.preventDefault(),ie.up(),vt()},[vt,ie]),we=f.useCallback(xe=>{xe.preventDefault(),ie.down(),vt()},[vt,ie]);Yi(()=>K.current,"wheel",xe=>{var ht,$t;const Ne=(($t=(ht=K.current)==null?void 0:ht.ownerDocument)!=null?$t:document).activeElement===K.current;if(!b||!Ne)return;xe.preventDefault();const qe=He(xe)*a,Pn=Math.sign(xe.deltaY);Pn===-1?ge(qe):Pn===1&&_e(qe)},{passive:!1});const Re=f.useCallback((xe={},ht=null)=>{const $t=d||r&&L.isAtMax;return{...xe,ref:cn(ht,se),role:"button",tabIndex:-1,onPointerDown:et(xe.onPointerDown,zt=>{zt.button!==0||$t||bt(zt)}),onPointerLeave:et(xe.onPointerLeave,ie.stop),onPointerUp:et(xe.onPointerUp,ie.stop),disabled:$t,"aria-disabled":ns($t)}},[L.isAtMax,r,bt,ie.stop,d]),Pt=f.useCallback((xe={},ht=null)=>{const $t=d||r&&L.isAtMin;return{...xe,ref:cn(ht,re),role:"button",tabIndex:-1,onPointerDown:et(xe.onPointerDown,zt=>{zt.button!==0||$t||we(zt)}),onPointerLeave:et(xe.onPointerLeave,ie.stop),onPointerUp:et(xe.onPointerUp,ie.stop),disabled:$t,"aria-disabled":ns($t)}},[L.isAtMin,r,we,ie.stop,d]),At=f.useCallback((xe={},ht=null)=>{var $t,zt,Ne,qe;return{name:k,inputMode:v,type:"text",pattern:m,"aria-labelledby":P,"aria-label":I,"aria-describedby":_,id:w,disabled:d,...xe,readOnly:($t=xe.readOnly)!=null?$t:c,"aria-readonly":(zt=xe.readOnly)!=null?zt:c,"aria-required":(Ne=xe.required)!=null?Ne:p,required:(qe=xe.required)!=null?qe:p,ref:cn(K,ht),value:le(L.value),role:"spinbutton","aria-valuemin":o,"aria-valuemax":s,"aria-valuenow":Number.isNaN(L.valueAsNumber)?void 0:L.valueAsNumber,"aria-invalid":ns(h??L.isOutOfRange),"aria-valuetext":Ct,autoComplete:"off",autoCorrect:"off",onChange:et(xe.onChange,Se),onKeyDown:et(xe.onKeyDown,Ae),onFocus:et(xe.onFocus,Fe,()=>ue(!0)),onBlur:et(xe.onBlur,V,on)}},[k,v,m,P,I,le,_,w,d,p,c,h,L.value,L.valueAsNumber,L.isOutOfRange,o,s,Ct,Se,Ae,Fe,V,on]);return{value:le(L.value),valueAsNumber:L.valueAsNumber,isFocused:ye,isDisabled:d,isReadOnly:c,getIncrementButtonProps:Re,getDecrementButtonProps:Pt,getInputProps:At,htmlProps:Q}}var[PL,um]=Rn({name:"NumberInputStylesContext",errorMessage:`useNumberInputStyles returned is 'undefined'. Seems you forgot to wrap the components in "" `}),[jL,Rb]=Rn({name:"NumberInputContext",errorMessage:"useNumberInputContext: `context` is undefined. Seems you forgot to wrap number-input's components within "}),dm=Te(function(t,n){const r=Br("NumberInput",t),o=qn(t),s=eb(o),{htmlProps:a,...c}=_L(s),d=f.useMemo(()=>c,[c]);return i.jsx(jL,{value:d,children:i.jsx(PL,{value:r,children:i.jsx(Ie.div,{...a,ref:n,className:kt("chakra-numberinput",t.className),__css:{position:"relative",zIndex:0,...r.root}})})})});dm.displayName="NumberInput";var fm=Te(function(t,n){const r=um();return i.jsx(Ie.div,{"aria-hidden":!0,ref:n,...t,__css:{display:"flex",flexDirection:"column",position:"absolute",top:"0",insetEnd:"0px",margin:"1px",height:"calc(100% - 2px)",zIndex:1,...r.stepperGroup}})});fm.displayName="NumberInputStepper";var pm=Te(function(t,n){const{getInputProps:r}=Rb(),o=r(t,n),s=um();return i.jsx(Ie.input,{...o,className:kt("chakra-numberinput__field",t.className),__css:{width:"100%",...s.field}})});pm.displayName="NumberInputField";var b5=Ie("div",{baseStyle:{display:"flex",justifyContent:"center",alignItems:"center",flex:1,transitionProperty:"common",transitionDuration:"normal",userSelect:"none",cursor:"pointer",lineHeight:"normal"}}),hm=Te(function(t,n){var r;const o=um(),{getDecrementButtonProps:s}=Rb(),a=s(t,n);return i.jsx(b5,{...a,__css:o.stepper,children:(r=t.children)!=null?r:i.jsx(vL,{})})});hm.displayName="NumberDecrementStepper";var mm=Te(function(t,n){var r;const{getIncrementButtonProps:o}=Rb(),s=o(t,n),a=um();return i.jsx(b5,{...s,__css:a.stepper,children:(r=t.children)!=null?r:i.jsx(bL,{})})});mm.displayName="NumberIncrementStepper";var[IL,Id]=Rn({name:"PopoverContext",errorMessage:"usePopoverContext: `context` is undefined. Seems you forgot to wrap all popover components within ``"}),[EL,Mb]=Rn({name:"PopoverStylesContext",errorMessage:`usePopoverStyles returned is 'undefined'. Seems you forgot to wrap the components in "" `});function Db(e){const t=f.Children.only(e.children),{getTriggerProps:n}=Id();return f.cloneElement(t,n(t.props,t.ref))}Db.displayName="PopoverTrigger";var zl={click:"click",hover:"hover"};function OL(e={}){const{closeOnBlur:t=!0,closeOnEsc:n=!0,initialFocusRef:r,id:o,returnFocusOnClose:s=!0,autoFocus:a=!0,arrowSize:c,arrowShadowColor:d,trigger:p=zl.click,openDelay:h=200,closeDelay:m=200,isLazy:v,lazyBehavior:b="unmount",computePositionOnMount:w,...y}=e,{isOpen:S,onClose:k,onOpen:_,onToggle:I}=jb(e),P=f.useRef(null),E=f.useRef(null),O=f.useRef(null),R=f.useRef(!1),M=f.useRef(!1);S&&(M.current=!0);const[T,A]=f.useState(!1),[$,Q]=f.useState(!1),B=f.useId(),V=o??B,[q,G,D,L]=["popover-trigger","popover-content","popover-header","popover-body"].map(Se=>`${Se}-${V}`),{referenceRef:W,getArrowProps:Y,getPopperProps:ae,getArrowInnerProps:ye,forceUpdate:ue}=Pb({...y,enabled:S||!!w}),X=r5({isOpen:S,ref:O});Q3({enabled:S,ref:E}),GP(O,{focusRef:E,visible:S,shouldFocus:s&&p===zl.click}),$N(O,{focusRef:r,visible:S,shouldFocus:a&&p===zl.click});const K=Ib({wasSelected:M.current,enabled:v,mode:b,isSelected:X.present}),U=f.useCallback((Se={},Fe=null)=>{const Ae={...Se,style:{...Se.style,transformOrigin:Pr.transformOrigin.varRef,[Pr.arrowSize.var]:c?`${c}px`:void 0,[Pr.arrowShadowColor.var]:d},ref:cn(O,Fe),children:K?Se.children:null,id:G,tabIndex:-1,role:"dialog",onKeyDown:et(Se.onKeyDown,He=>{n&&He.key==="Escape"&&k()}),onBlur:et(Se.onBlur,He=>{const Ct=rS(He),ct=C0(O.current,Ct),on=C0(E.current,Ct);S&&t&&(!ct&&!on)&&k()}),"aria-labelledby":T?D:void 0,"aria-describedby":$?L:void 0};return p===zl.hover&&(Ae.role="tooltip",Ae.onMouseEnter=et(Se.onMouseEnter,()=>{R.current=!0}),Ae.onMouseLeave=et(Se.onMouseLeave,He=>{He.nativeEvent.relatedTarget!==null&&(R.current=!1,setTimeout(()=>k(),m))})),Ae},[K,G,T,D,$,L,p,n,k,S,t,m,d,c]),se=f.useCallback((Se={},Fe=null)=>ae({...Se,style:{visibility:S?"visible":"hidden",...Se.style}},Fe),[S,ae]),re=f.useCallback((Se,Fe=null)=>({...Se,ref:cn(Fe,P,W)}),[P,W]),oe=f.useRef(),pe=f.useRef(),le=f.useCallback(Se=>{P.current==null&&W(Se)},[W]),ge=f.useCallback((Se={},Fe=null)=>{const Ae={...Se,ref:cn(E,Fe,le),id:q,"aria-haspopup":"dialog","aria-expanded":S,"aria-controls":G};return p===zl.click&&(Ae.onClick=et(Se.onClick,I)),p===zl.hover&&(Ae.onFocus=et(Se.onFocus,()=>{oe.current===void 0&&_()}),Ae.onBlur=et(Se.onBlur,He=>{const Ct=rS(He),ct=!C0(O.current,Ct);S&&t&&ct&&k()}),Ae.onKeyDown=et(Se.onKeyDown,He=>{He.key==="Escape"&&k()}),Ae.onMouseEnter=et(Se.onMouseEnter,()=>{R.current=!0,oe.current=window.setTimeout(()=>_(),h)}),Ae.onMouseLeave=et(Se.onMouseLeave,()=>{R.current=!1,oe.current&&(clearTimeout(oe.current),oe.current=void 0),pe.current=window.setTimeout(()=>{R.current===!1&&k()},m)})),Ae},[q,S,G,p,le,I,_,t,k,h,m]);f.useEffect(()=>()=>{oe.current&&clearTimeout(oe.current),pe.current&&clearTimeout(pe.current)},[]);const _e=f.useCallback((Se={},Fe=null)=>({...Se,id:D,ref:cn(Fe,Ae=>{A(!!Ae)})}),[D]),ie=f.useCallback((Se={},Fe=null)=>({...Se,id:L,ref:cn(Fe,Ae=>{Q(!!Ae)})}),[L]);return{forceUpdate:ue,isOpen:S,onAnimationComplete:X.onComplete,onClose:k,getAnchorProps:re,getArrowProps:Y,getArrowInnerProps:ye,getPopoverPositionerProps:se,getPopoverProps:U,getTriggerProps:ge,getHeaderProps:_e,getBodyProps:ie}}function C0(e,t){return e===t||(e==null?void 0:e.contains(t))}function rS(e){var t;const n=e.currentTarget.ownerDocument.activeElement;return(t=e.relatedTarget)!=null?t:n}function Tb(e){const t=Br("Popover",e),{children:n,...r}=qn(e),o=Mc(),s=OL({...r,direction:o.direction});return i.jsx(IL,{value:s,children:i.jsx(EL,{value:t,children:D1(n,{isOpen:s.isOpen,onClose:s.onClose,forceUpdate:s.forceUpdate})})})}Tb.displayName="Popover";var k0=(e,t)=>t?`${e}.${t}, ${t}`:void 0;function y5(e){var t;const{bg:n,bgColor:r,backgroundColor:o,shadow:s,boxShadow:a,shadowColor:c}=e,{getArrowProps:d,getArrowInnerProps:p}=Id(),h=Mb(),m=(t=n??r)!=null?t:o,v=s??a;return i.jsx(Ie.div,{...d(),className:"chakra-popover__arrow-positioner",children:i.jsx(Ie.div,{className:kt("chakra-popover__arrow",e.className),...p(e),__css:{"--popper-arrow-shadow-color":k0("colors",c),"--popper-arrow-bg":k0("colors",m),"--popper-arrow-shadow":k0("shadows",v),...h.arrow}})})}y5.displayName="PopoverArrow";var x5=Te(function(t,n){const{getBodyProps:r}=Id(),o=Mb();return i.jsx(Ie.div,{...r(t,n),className:kt("chakra-popover__body",t.className),__css:o.body})});x5.displayName="PopoverBody";function RL(e){if(e)return{enter:{...e.enter,visibility:"visible"},exit:{...e.exit,transitionEnd:{visibility:"hidden"}}}}var ML={exit:{opacity:0,scale:.95,transition:{duration:.1,ease:[.4,0,1,1]}},enter:{scale:1,opacity:1,transition:{duration:.15,ease:[0,0,.2,1]}}},DL=Ie(Xr.section),w5=Te(function(t,n){const{variants:r=ML,...o}=t,{isOpen:s}=Id();return i.jsx(DL,{ref:n,variants:RL(r),initial:!1,animate:s?"enter":"exit",...o})});w5.displayName="PopoverTransition";var Ab=Te(function(t,n){const{rootProps:r,motionProps:o,...s}=t,{getPopoverProps:a,getPopoverPositionerProps:c,onAnimationComplete:d}=Id(),p=Mb(),h={position:"relative",display:"flex",flexDirection:"column",...p.content};return i.jsx(Ie.div,{...c(r),__css:p.popper,className:"chakra-popover__popper",children:i.jsx(w5,{...o,...a(s,n),onAnimationComplete:Jh(d,s.onAnimationComplete),className:kt("chakra-popover__content",t.className),__css:h})})});Ab.displayName="PopoverContent";function TL(e,t,n){return(e-t)*100/(n-t)}za({"0%":{strokeDasharray:"1, 400",strokeDashoffset:"0"},"50%":{strokeDasharray:"400, 400",strokeDashoffset:"-100"},"100%":{strokeDasharray:"400, 400",strokeDashoffset:"-260"}});za({"0%":{transform:"rotate(0deg)"},"100%":{transform:"rotate(360deg)"}});var AL=za({"0%":{left:"-40%"},"100%":{left:"100%"}}),NL=za({from:{backgroundPosition:"1rem 0"},to:{backgroundPosition:"0 0"}});function $L(e){const{value:t=0,min:n,max:r,valueText:o,getValueText:s,isIndeterminate:a,role:c="progressbar"}=e,d=TL(t,n,r);return{bind:{"data-indeterminate":a?"":void 0,"aria-valuemax":r,"aria-valuemin":n,"aria-valuenow":a?void 0:t,"aria-valuetext":(()=>{if(t!=null)return typeof s=="function"?s(t,d):o})(),role:c},percent:d,value:t}}var[zL,LL]=Rn({name:"ProgressStylesContext",errorMessage:`useProgressStyles returned is 'undefined'. Seems you forgot to wrap the components in "" `}),BL=Te((e,t)=>{const{min:n,max:r,value:o,isIndeterminate:s,role:a,...c}=e,d=$L({value:o,min:n,max:r,isIndeterminate:s,role:a}),h={height:"100%",...LL().filledTrack};return i.jsx(Ie.div,{ref:t,style:{width:`${d.percent}%`,...c.style},...d.bind,...c,__css:h})}),S5=Te((e,t)=>{var n;const{value:r,min:o=0,max:s=100,hasStripe:a,isAnimated:c,children:d,borderRadius:p,isIndeterminate:h,"aria-label":m,"aria-labelledby":v,"aria-valuetext":b,title:w,role:y,...S}=qn(e),k=Br("Progress",e),_=p??((n=k.track)==null?void 0:n.borderRadius),I={animation:`${NL} 1s linear infinite`},O={...!h&&a&&c&&I,...h&&{position:"absolute",willChange:"left",minWidth:"50%",animation:`${AL} 1s ease infinite normal none running`}},R={overflow:"hidden",position:"relative",...k.track};return i.jsx(Ie.div,{ref:t,borderRadius:_,__css:R,...S,children:i.jsxs(zL,{value:k,children:[i.jsx(BL,{"aria-label":m,"aria-labelledby":v,"aria-valuetext":b,min:o,max:s,value:r,isIndeterminate:h,css:O,borderRadius:_,title:w,role:y}),d]})})});S5.displayName="Progress";function FL(e){return e&&pv(e)&&pv(e.target)}function HL(e={}){const{onChange:t,value:n,defaultValue:r,name:o,isDisabled:s,isFocusable:a,isNative:c,...d}=e,[p,h]=f.useState(r||""),m=typeof n<"u",v=m?n:p,b=f.useRef(null),w=f.useCallback(()=>{const E=b.current;if(!E)return;let O="input:not(:disabled):checked";const R=E.querySelector(O);if(R){R.focus();return}O="input:not(:disabled)";const M=E.querySelector(O);M==null||M.focus()},[]),S=`radio-${f.useId()}`,k=o||S,_=f.useCallback(E=>{const O=FL(E)?E.target.value:E;m||h(O),t==null||t(String(O))},[t,m]),I=f.useCallback((E={},O=null)=>({...E,ref:cn(O,b),role:"radiogroup"}),[]),P=f.useCallback((E={},O=null)=>({...E,ref:O,name:k,[c?"checked":"isChecked"]:v!=null?E.value===v:void 0,onChange(M){_(M)},"data-radiogroup":!0}),[c,k,_,v]);return{getRootProps:I,getRadioProps:P,name:k,ref:b,focus:w,setValue:h,value:v,onChange:_,isDisabled:s,isFocusable:a,htmlProps:d}}var[WL,C5]=Rn({name:"RadioGroupContext",strict:!1}),Gp=Te((e,t)=>{const{colorScheme:n,size:r,variant:o,children:s,className:a,isDisabled:c,isFocusable:d,...p}=e,{value:h,onChange:m,getRootProps:v,name:b,htmlProps:w}=HL(p),y=f.useMemo(()=>({name:b,size:r,onChange:m,colorScheme:n,value:h,variant:o,isDisabled:c,isFocusable:d}),[b,r,m,n,h,o,c,d]);return i.jsx(WL,{value:y,children:i.jsx(Ie.div,{...v(w,t),className:kt("chakra-radio-group",a),children:s})})});Gp.displayName="RadioGroup";var VL={border:"0",clip:"rect(0, 0, 0, 0)",height:"1px",width:"1px",margin:"-1px",padding:"0",overflow:"hidden",whiteSpace:"nowrap",position:"absolute"};function UL(e={}){const{defaultChecked:t,isChecked:n,isFocusable:r,isDisabled:o,isReadOnly:s,isRequired:a,onChange:c,isInvalid:d,name:p,value:h,id:m,"data-radiogroup":v,"aria-describedby":b,...w}=e,y=`radio-${f.useId()}`,S=vd(),_=!!C5()||!!v;let P=!!S&&!_?S.id:y;P=m??P;const E=o??(S==null?void 0:S.isDisabled),O=s??(S==null?void 0:S.isReadOnly),R=a??(S==null?void 0:S.isRequired),M=d??(S==null?void 0:S.isInvalid),[T,A]=f.useState(!1),[$,Q]=f.useState(!1),[B,V]=f.useState(!1),[q,G]=f.useState(!1),[D,L]=f.useState(!!t),W=typeof n<"u",Y=W?n:D;f.useEffect(()=>B3(A),[]);const ae=f.useCallback(le=>{if(O||E){le.preventDefault();return}W||L(le.target.checked),c==null||c(le)},[W,E,O,c]),ye=f.useCallback(le=>{le.key===" "&&G(!0)},[G]),ue=f.useCallback(le=>{le.key===" "&&G(!1)},[G]),X=f.useCallback((le={},ge=null)=>({...le,ref:ge,"data-active":tn(q),"data-hover":tn(B),"data-disabled":tn(E),"data-invalid":tn(M),"data-checked":tn(Y),"data-focus":tn($),"data-focus-visible":tn($&&T),"data-readonly":tn(O),"aria-hidden":!0,onMouseDown:et(le.onMouseDown,()=>G(!0)),onMouseUp:et(le.onMouseUp,()=>G(!1)),onMouseEnter:et(le.onMouseEnter,()=>V(!0)),onMouseLeave:et(le.onMouseLeave,()=>V(!1))}),[q,B,E,M,Y,$,O,T]),{onFocus:K,onBlur:U}=S??{},se=f.useCallback((le={},ge=null)=>{const _e=E&&!r;return{...le,id:P,ref:ge,type:"radio",name:p,value:h,onChange:et(le.onChange,ae),onBlur:et(U,le.onBlur,()=>Q(!1)),onFocus:et(K,le.onFocus,()=>Q(!0)),onKeyDown:et(le.onKeyDown,ye),onKeyUp:et(le.onKeyUp,ue),checked:Y,disabled:_e,readOnly:O,required:R,"aria-invalid":ns(M),"aria-disabled":ns(_e),"aria-required":ns(R),"data-readonly":tn(O),"aria-describedby":b,style:VL}},[E,r,P,p,h,ae,U,K,ye,ue,Y,O,R,M,b]);return{state:{isInvalid:M,isFocused:$,isChecked:Y,isActive:q,isHovered:B,isDisabled:E,isReadOnly:O,isRequired:R},getCheckboxProps:X,getRadioProps:X,getInputProps:se,getLabelProps:(le={},ge=null)=>({...le,ref:ge,onMouseDown:et(le.onMouseDown,GL),"data-disabled":tn(E),"data-checked":tn(Y),"data-invalid":tn(M)}),getRootProps:(le,ge=null)=>({...le,ref:ge,"data-disabled":tn(E),"data-checked":tn(Y),"data-invalid":tn(M)}),htmlProps:w}}function GL(e){e.preventDefault(),e.stopPropagation()}function qL(e,t){const n={},r={};for(const[o,s]of Object.entries(e))t.includes(o)?n[o]=s:r[o]=s;return[n,r]}var ba=Te((e,t)=>{var n;const r=C5(),{onChange:o,value:s}=e,a=Br("Radio",{...r,...e}),c=qn(e),{spacing:d="0.5rem",children:p,isDisabled:h=r==null?void 0:r.isDisabled,isFocusable:m=r==null?void 0:r.isFocusable,inputProps:v,...b}=c;let w=e.isChecked;(r==null?void 0:r.value)!=null&&s!=null&&(w=r.value===s);let y=o;r!=null&&r.onChange&&s!=null&&(y=Jh(r.onChange,o));const S=(n=e==null?void 0:e.name)!=null?n:r==null?void 0:r.name,{getInputProps:k,getCheckboxProps:_,getLabelProps:I,getRootProps:P,htmlProps:E}=UL({...b,isChecked:w,isFocusable:m,isDisabled:h,onChange:y,name:S}),[O,R]=qL(E,__),M=_(R),T=k(v,t),A=I(),$=Object.assign({},O,P()),Q={display:"inline-flex",alignItems:"center",verticalAlign:"top",cursor:"pointer",position:"relative",...a.container},B={display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,...a.control},V={userSelect:"none",marginStart:d,...a.label};return i.jsxs(Ie.label,{className:"chakra-radio",...$,__css:Q,children:[i.jsx("input",{className:"chakra-radio__input",...T}),i.jsx(Ie.span,{className:"chakra-radio__control",...M,__css:B}),p&&i.jsx(Ie.span,{className:"chakra-radio__label",...A,__css:V,children:p})]})});ba.displayName="Radio";var k5=Te(function(t,n){const{children:r,placeholder:o,className:s,...a}=t;return i.jsxs(Ie.select,{...a,ref:n,className:kt("chakra-select",s),children:[o&&i.jsx("option",{value:"",children:o}),r]})});k5.displayName="SelectField";function KL(e,t){const n={},r={};for(const[o,s]of Object.entries(e))t.includes(o)?n[o]=s:r[o]=s;return[n,r]}var _5=Te((e,t)=>{var n;const r=Br("Select",e),{rootProps:o,placeholder:s,icon:a,color:c,height:d,h:p,minH:h,minHeight:m,iconColor:v,iconSize:b,...w}=qn(e),[y,S]=KL(w,__),k=Z1(S),_={width:"100%",height:"fit-content",position:"relative",color:c},I={paddingEnd:"2rem",...r.field,_focus:{zIndex:"unset",...(n=r.field)==null?void 0:n._focus}};return i.jsxs(Ie.div,{className:"chakra-select__wrapper",__css:_,...y,...o,children:[i.jsx(k5,{ref:t,height:p??d,minH:h??m,placeholder:s,...k,__css:I,children:e.children}),i.jsx(P5,{"data-disabled":tn(k.disabled),...(v||c)&&{color:v||c},__css:r.icon,...b&&{fontSize:b},children:a})]})});_5.displayName="Select";var YL=e=>i.jsx("svg",{viewBox:"0 0 24 24",...e,children:i.jsx("path",{fill:"currentColor",d:"M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"})}),XL=Ie("div",{baseStyle:{position:"absolute",display:"inline-flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",top:"50%",transform:"translateY(-50%)"}}),P5=e=>{const{children:t=i.jsx(YL,{}),...n}=e,r=f.cloneElement(t,{role:"presentation",className:"chakra-select__icon",focusable:!1,"aria-hidden":!0,style:{width:"1em",height:"1em",color:"currentColor"}});return i.jsx(XL,{...n,className:"chakra-select__icon-wrapper",children:f.isValidElement(t)?r:null})};P5.displayName="SelectIcon";function QL(){const e=f.useRef(!0);return f.useEffect(()=>{e.current=!1},[]),e.current}function JL(e){const t=f.useRef();return f.useEffect(()=>{t.current=e},[e]),t.current}var ZL=Ie("div",{baseStyle:{boxShadow:"none",backgroundClip:"padding-box",cursor:"default",color:"transparent",pointerEvents:"none",userSelect:"none","&::before, &::after, *":{visibility:"hidden"}}}),Bv=P_("skeleton-start-color"),Fv=P_("skeleton-end-color"),eB=za({from:{opacity:0},to:{opacity:1}}),tB=za({from:{borderColor:Bv.reference,background:Bv.reference},to:{borderColor:Fv.reference,background:Fv.reference}}),gm=Te((e,t)=>{const n={...e,fadeDuration:typeof e.fadeDuration=="number"?e.fadeDuration:.4,speed:typeof e.speed=="number"?e.speed:.8},r=$a("Skeleton",n),o=QL(),{startColor:s="",endColor:a="",isLoaded:c,fadeDuration:d,speed:p,className:h,fitContent:m,...v}=qn(n),[b,w]=Dc("colors",[s,a]),y=JL(c),S=kt("chakra-skeleton",h),k={...b&&{[Bv.variable]:b},...w&&{[Fv.variable]:w}};if(c){const _=o||y?"none":`${eB} ${d}s`;return i.jsx(Ie.div,{ref:t,className:S,__css:{animation:_},...v})}return i.jsx(ZL,{ref:t,className:S,...v,__css:{width:m?"fit-content":void 0,...r,...k,_dark:{...r._dark,...k},animation:`${p}s linear infinite alternate ${tB}`}})});gm.displayName="Skeleton";var Jo=e=>e?"":void 0,ic=e=>e?!0:void 0,ji=(...e)=>e.filter(Boolean).join(" ");function lc(...e){return function(n){e.some(r=>(r==null||r(n),n==null?void 0:n.defaultPrevented))}}function nB(e){return{root:`slider-root-${e}`,getThumb:t=>`slider-thumb-${e}-${t}`,getInput:t=>`slider-input-${e}-${t}`,track:`slider-track-${e}`,innerTrack:`slider-filled-track-${e}`,getMarker:t=>`slider-marker-${e}-${t}`,output:`slider-output-${e}`}}function Pu(e){const{orientation:t,vertical:n,horizontal:r}=e;return t==="vertical"?n:r}var Sp={width:0,height:0},$f=e=>e||Sp;function j5(e){const{orientation:t,thumbPercents:n,thumbRects:r,isReversed:o}=e,s=y=>{var S;const k=(S=r[y])!=null?S:Sp;return{position:"absolute",userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none",touchAction:"none",...Pu({orientation:t,vertical:{bottom:`calc(${n[y]}% - ${k.height/2}px)`},horizontal:{left:`calc(${n[y]}% - ${k.width/2}px)`}})}},a=t==="vertical"?r.reduce((y,S)=>$f(y).height>$f(S).height?y:S,Sp):r.reduce((y,S)=>$f(y).width>$f(S).width?y:S,Sp),c={position:"relative",touchAction:"none",WebkitTapHighlightColor:"rgba(0,0,0,0)",userSelect:"none",outline:0,...Pu({orientation:t,vertical:a?{paddingLeft:a.width/2,paddingRight:a.width/2}:{},horizontal:a?{paddingTop:a.height/2,paddingBottom:a.height/2}:{}})},d={position:"absolute",...Pu({orientation:t,vertical:{left:"50%",transform:"translateX(-50%)",height:"100%"},horizontal:{top:"50%",transform:"translateY(-50%)",width:"100%"}})},p=n.length===1,h=[0,o?100-n[0]:n[0]],m=p?h:n;let v=m[0];!p&&o&&(v=100-v);const b=Math.abs(m[m.length-1]-m[0]),w={...d,...Pu({orientation:t,vertical:o?{height:`${b}%`,top:`${v}%`}:{height:`${b}%`,bottom:`${v}%`},horizontal:o?{width:`${b}%`,right:`${v}%`}:{width:`${b}%`,left:`${v}%`}})};return{trackStyle:d,innerTrackStyle:w,rootStyle:c,getThumbStyle:s}}function I5(e){const{isReversed:t,direction:n,orientation:r}=e;return n==="ltr"||r==="vertical"?t:!t}function rB(e,t,n,r){return e.addEventListener(t,n,r),()=>{e.removeEventListener(t,n,r)}}function oB(e){const t=aB(e);return typeof t.PointerEvent<"u"&&e instanceof t.PointerEvent?e.pointerType==="mouse":e instanceof t.MouseEvent}function E5(e){return!!e.touches}function sB(e){return E5(e)&&e.touches.length>1}function aB(e){var t;return(t=e.view)!=null?t:window}function iB(e,t="page"){const n=e.touches[0]||e.changedTouches[0];return{x:n[`${t}X`],y:n[`${t}Y`]}}function lB(e,t="page"){return{x:e[`${t}X`],y:e[`${t}Y`]}}function O5(e,t="page"){return E5(e)?iB(e,t):lB(e,t)}function cB(e){return t=>{const n=oB(t);(!n||n&&t.button===0)&&e(t)}}function uB(e,t=!1){function n(o){e(o,{point:O5(o)})}return t?cB(n):n}function Cp(e,t,n,r){return rB(e,t,uB(n,t==="pointerdown"),r)}var dB=Object.defineProperty,fB=(e,t,n)=>t in e?dB(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,bs=(e,t,n)=>(fB(e,typeof t!="symbol"?t+"":t,n),n),pB=class{constructor(e,t,n){bs(this,"history",[]),bs(this,"startEvent",null),bs(this,"lastEvent",null),bs(this,"lastEventInfo",null),bs(this,"handlers",{}),bs(this,"removeListeners",()=>{}),bs(this,"threshold",3),bs(this,"win"),bs(this,"updatePoint",()=>{if(!(this.lastEvent&&this.lastEventInfo))return;const c=_0(this.lastEventInfo,this.history),d=this.startEvent!==null,p=vB(c.offset,{x:0,y:0})>=this.threshold;if(!d&&!p)return;const{timestamp:h}=bw();this.history.push({...c.point,timestamp:h});const{onStart:m,onMove:v}=this.handlers;d||(m==null||m(this.lastEvent,c),this.startEvent=this.lastEvent),v==null||v(this.lastEvent,c)}),bs(this,"onPointerMove",(c,d)=>{this.lastEvent=c,this.lastEventInfo=d,NT.update(this.updatePoint,!0)}),bs(this,"onPointerUp",(c,d)=>{const p=_0(d,this.history),{onEnd:h,onSessionEnd:m}=this.handlers;m==null||m(c,p),this.end(),!(!h||!this.startEvent)&&(h==null||h(c,p))});var r;if(this.win=(r=e.view)!=null?r:window,sB(e))return;this.handlers=t,n&&(this.threshold=n),e.stopPropagation(),e.preventDefault();const o={point:O5(e)},{timestamp:s}=bw();this.history=[{...o.point,timestamp:s}];const{onSessionStart:a}=t;a==null||a(e,_0(o,this.history)),this.removeListeners=gB(Cp(this.win,"pointermove",this.onPointerMove),Cp(this.win,"pointerup",this.onPointerUp),Cp(this.win,"pointercancel",this.onPointerUp))}updateHandlers(e){this.handlers=e}end(){var e;(e=this.removeListeners)==null||e.call(this),$T.update(this.updatePoint)}};function oS(e,t){return{x:e.x-t.x,y:e.y-t.y}}function _0(e,t){return{point:e.point,delta:oS(e.point,t[t.length-1]),offset:oS(e.point,t[0]),velocity:mB(t,.1)}}var hB=e=>e*1e3;function mB(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null;const o=e[e.length-1];for(;n>=0&&(r=e[n],!(o.timestamp-r.timestamp>hB(t)));)n--;if(!r)return{x:0,y:0};const s=(o.timestamp-r.timestamp)/1e3;if(s===0)return{x:0,y:0};const a={x:(o.x-r.x)/s,y:(o.y-r.y)/s};return a.x===1/0&&(a.x=0),a.y===1/0&&(a.y=0),a}function gB(...e){return t=>e.reduce((n,r)=>r(n),t)}function P0(e,t){return Math.abs(e-t)}function sS(e){return"x"in e&&"y"in e}function vB(e,t){if(typeof e=="number"&&typeof t=="number")return P0(e,t);if(sS(e)&&sS(t)){const n=P0(e.x,t.x),r=P0(e.y,t.y);return Math.sqrt(n**2+r**2)}return 0}function R5(e){const t=f.useRef(null);return t.current=e,t}function M5(e,t){const{onPan:n,onPanStart:r,onPanEnd:o,onPanSessionStart:s,onPanSessionEnd:a,threshold:c}=t,d=!!(n||r||o||s||a),p=f.useRef(null),h=R5({onSessionStart:s,onSessionEnd:a,onStart:r,onMove:n,onEnd(m,v){p.current=null,o==null||o(m,v)}});f.useEffect(()=>{var m;(m=p.current)==null||m.updateHandlers(h.current)}),f.useEffect(()=>{const m=e.current;if(!m||!d)return;function v(b){p.current=new pB(b,h.current,c)}return Cp(m,"pointerdown",v)},[e,d,h,c]),f.useEffect(()=>()=>{var m;(m=p.current)==null||m.end(),p.current=null},[])}function bB(e,t){if(!e){t(void 0);return}t({width:e.offsetWidth,height:e.offsetHeight});const n=e.ownerDocument.defaultView??window,r=new n.ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const[s]=o;let a,c;if("borderBoxSize"in s){const d=s.borderBoxSize,p=Array.isArray(d)?d[0]:d;a=p.inlineSize,c=p.blockSize}else a=e.offsetWidth,c=e.offsetHeight;t({width:a,height:c})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}var yB=globalThis!=null&&globalThis.document?f.useLayoutEffect:f.useEffect;function xB(e,t){var n,r;if(!e||!e.parentElement)return;const o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?r:window,s=new o.MutationObserver(()=>{t()});return s.observe(e.parentElement,{childList:!0}),()=>{s.disconnect()}}function D5({getNodes:e,observeMutation:t=!0}){const[n,r]=f.useState([]),[o,s]=f.useState(0);return yB(()=>{const a=e(),c=a.map((d,p)=>bB(d,h=>{r(m=>[...m.slice(0,p),h,...m.slice(p+1)])}));if(t){const d=a[0];c.push(xB(d,()=>{s(p=>p+1)}))}return()=>{c.forEach(d=>{d==null||d()})}},[o]),n}function wB(e){return typeof e=="object"&&e!==null&&"current"in e}function SB(e){const[t]=D5({observeMutation:!1,getNodes(){return[wB(e)?e.current:e]}});return t}function CB(e){const{min:t=0,max:n=100,onChange:r,value:o,defaultValue:s,isReversed:a,direction:c="ltr",orientation:d="horizontal",id:p,isDisabled:h,isReadOnly:m,onChangeStart:v,onChangeEnd:b,step:w=1,getAriaValueText:y,"aria-valuetext":S,"aria-label":k,"aria-labelledby":_,name:I,focusThumbOnChange:P=!0,minStepsBetweenThumbs:E=0,...O}=e,R=rr(v),M=rr(b),T=rr(y),A=I5({isReversed:a,direction:c,orientation:d}),[$,Q]=Ac({value:o,defaultValue:s??[25,75],onChange:r});if(!Array.isArray($))throw new TypeError(`[range-slider] You passed an invalid value for \`value\` or \`defaultValue\`, expected \`Array\` but got \`${typeof $}\``);const[B,V]=f.useState(!1),[q,G]=f.useState(!1),[D,L]=f.useState(-1),W=!(h||m),Y=f.useRef($),ae=$.map(Pe=>rc(Pe,t,n)),ye=E*w,ue=kB(ae,t,n,ye),X=f.useRef({eventSource:null,value:[],valueBounds:[]});X.current.value=ae,X.current.valueBounds=ue;const K=ae.map(Pe=>n-Pe+t),se=(A?K:ae).map(Pe=>Bp(Pe,t,n)),re=d==="vertical",oe=f.useRef(null),pe=f.useRef(null),le=D5({getNodes(){const Pe=pe.current,Je=Pe==null?void 0:Pe.querySelectorAll("[role=slider]");return Je?Array.from(Je):[]}}),ge=f.useId(),ie=nB(p??ge),Se=f.useCallback(Pe=>{var Je,Xe;if(!oe.current)return;X.current.eventSource="pointer";const dt=oe.current.getBoundingClientRect(),{clientX:Lt,clientY:lr}=(Xe=(Je=Pe.touches)==null?void 0:Je[0])!=null?Xe:Pe,pn=re?dt.bottom-lr:Lt-dt.left,ln=re?dt.height:dt.width;let Fr=pn/ln;return A&&(Fr=1-Fr),W3(Fr,t,n)},[re,A,n,t]),Fe=(n-t)/10,Ae=w||(n-t)/100,He=f.useMemo(()=>({setValueAtIndex(Pe,Je){if(!W)return;const Xe=X.current.valueBounds[Pe];Je=parseFloat(Iv(Je,Xe.min,Ae)),Je=rc(Je,Xe.min,Xe.max);const dt=[...X.current.value];dt[Pe]=Je,Q(dt)},setActiveIndex:L,stepUp(Pe,Je=Ae){const Xe=X.current.value[Pe],dt=A?Xe-Je:Xe+Je;He.setValueAtIndex(Pe,dt)},stepDown(Pe,Je=Ae){const Xe=X.current.value[Pe],dt=A?Xe+Je:Xe-Je;He.setValueAtIndex(Pe,dt)},reset(){Q(Y.current)}}),[Ae,A,Q,W]),Ct=f.useCallback(Pe=>{const Je=Pe.key,dt={ArrowRight:()=>He.stepUp(D),ArrowUp:()=>He.stepUp(D),ArrowLeft:()=>He.stepDown(D),ArrowDown:()=>He.stepDown(D),PageUp:()=>He.stepUp(D,Fe),PageDown:()=>He.stepDown(D,Fe),Home:()=>{const{min:Lt}=ue[D];He.setValueAtIndex(D,Lt)},End:()=>{const{max:Lt}=ue[D];He.setValueAtIndex(D,Lt)}}[Je];dt&&(Pe.preventDefault(),Pe.stopPropagation(),dt(Pe),X.current.eventSource="keyboard")},[He,D,Fe,ue]),{getThumbStyle:ct,rootStyle:on,trackStyle:vt,innerTrackStyle:bt}=f.useMemo(()=>j5({isReversed:A,orientation:d,thumbRects:le,thumbPercents:se}),[A,d,se,le]),we=f.useCallback(Pe=>{var Je;const Xe=Pe??D;if(Xe!==-1&&P){const dt=ie.getThumb(Xe),Lt=(Je=pe.current)==null?void 0:Je.ownerDocument.getElementById(dt);Lt&&setTimeout(()=>Lt.focus())}},[P,D,ie]);Ba(()=>{X.current.eventSource==="keyboard"&&(M==null||M(X.current.value))},[ae,M]);const Re=Pe=>{const Je=Se(Pe)||0,Xe=X.current.value.map(ln=>Math.abs(ln-Je)),dt=Math.min(...Xe);let Lt=Xe.indexOf(dt);const lr=Xe.filter(ln=>ln===dt);lr.length>1&&Je>X.current.value[Lt]&&(Lt=Lt+lr.length-1),L(Lt),He.setValueAtIndex(Lt,Je),we(Lt)},Pt=Pe=>{if(D==-1)return;const Je=Se(Pe)||0;L(D),He.setValueAtIndex(D,Je),we(D)};M5(pe,{onPanSessionStart(Pe){W&&(V(!0),Re(Pe),R==null||R(X.current.value))},onPanSessionEnd(){W&&(V(!1),M==null||M(X.current.value))},onPan(Pe){W&&Pt(Pe)}});const At=f.useCallback((Pe={},Je=null)=>({...Pe,...O,id:ie.root,ref:cn(Je,pe),tabIndex:-1,"aria-disabled":ic(h),"data-focused":Jo(q),style:{...Pe.style,...on}}),[O,h,q,on,ie]),xe=f.useCallback((Pe={},Je=null)=>({...Pe,ref:cn(Je,oe),id:ie.track,"data-disabled":Jo(h),style:{...Pe.style,...vt}}),[h,vt,ie]),ht=f.useCallback((Pe={},Je=null)=>({...Pe,ref:Je,id:ie.innerTrack,style:{...Pe.style,...bt}}),[bt,ie]),$t=f.useCallback((Pe,Je=null)=>{var Xe;const{index:dt,...Lt}=Pe,lr=ae[dt];if(lr==null)throw new TypeError(`[range-slider > thumb] Cannot find value at index \`${dt}\`. The \`value\` or \`defaultValue\` length is : ${ae.length}`);const pn=ue[dt];return{...Lt,ref:Je,role:"slider",tabIndex:W?0:void 0,id:ie.getThumb(dt),"data-active":Jo(B&&D===dt),"aria-valuetext":(Xe=T==null?void 0:T(lr))!=null?Xe:S==null?void 0:S[dt],"aria-valuemin":pn.min,"aria-valuemax":pn.max,"aria-valuenow":lr,"aria-orientation":d,"aria-disabled":ic(h),"aria-readonly":ic(m),"aria-label":k==null?void 0:k[dt],"aria-labelledby":k!=null&&k[dt]||_==null?void 0:_[dt],style:{...Pe.style,...ct(dt)},onKeyDown:lc(Pe.onKeyDown,Ct),onFocus:lc(Pe.onFocus,()=>{G(!0),L(dt)}),onBlur:lc(Pe.onBlur,()=>{G(!1),L(-1)})}},[ie,ae,ue,W,B,D,T,S,d,h,m,k,_,ct,Ct,G]),zt=f.useCallback((Pe={},Je=null)=>({...Pe,ref:Je,id:ie.output,htmlFor:ae.map((Xe,dt)=>ie.getThumb(dt)).join(" "),"aria-live":"off"}),[ie,ae]),Ne=f.useCallback((Pe,Je=null)=>{const{value:Xe,...dt}=Pe,Lt=!(Xen),lr=Xe>=ae[0]&&Xe<=ae[ae.length-1];let pn=Bp(Xe,t,n);pn=A?100-pn:pn;const ln={position:"absolute",pointerEvents:"none",...Pu({orientation:d,vertical:{bottom:`${pn}%`},horizontal:{left:`${pn}%`}})};return{...dt,ref:Je,id:ie.getMarker(Pe.value),role:"presentation","aria-hidden":!0,"data-disabled":Jo(h),"data-invalid":Jo(!Lt),"data-highlighted":Jo(lr),style:{...Pe.style,...ln}}},[h,A,n,t,d,ae,ie]),qe=f.useCallback((Pe,Je=null)=>{const{index:Xe,...dt}=Pe;return{...dt,ref:Je,id:ie.getInput(Xe),type:"hidden",value:ae[Xe],name:Array.isArray(I)?I[Xe]:`${I}-${Xe}`}},[I,ae,ie]);return{state:{value:ae,isFocused:q,isDragging:B,getThumbPercent:Pe=>se[Pe],getThumbMinValue:Pe=>ue[Pe].min,getThumbMaxValue:Pe=>ue[Pe].max},actions:He,getRootProps:At,getTrackProps:xe,getInnerTrackProps:ht,getThumbProps:$t,getMarkerProps:Ne,getInputProps:qe,getOutputProps:zt}}function kB(e,t,n,r){return e.map((o,s)=>{const a=s===0?t:e[s-1]+r,c=s===e.length-1?n:e[s+1]-r;return{min:a,max:c}})}var[_B,vm]=Rn({name:"SliderContext",errorMessage:"useSliderContext: `context` is undefined. Seems you forgot to wrap all slider components within "}),[PB,bm]=Rn({name:"RangeSliderStylesContext",errorMessage:`useRangeSliderStyles returned is 'undefined'. Seems you forgot to wrap the components in "" `}),T5=Te(function(t,n){const r={orientation:"horizontal",...t},o=Br("Slider",r),s=qn(r),{direction:a}=Mc();s.direction=a;const{getRootProps:c,...d}=CB(s),p=f.useMemo(()=>({...d,name:r.name}),[d,r.name]);return i.jsx(_B,{value:p,children:i.jsx(PB,{value:o,children:i.jsx(Ie.div,{...c({},n),className:"chakra-slider",__css:o.container,children:r.children})})})});T5.displayName="RangeSlider";var Hv=Te(function(t,n){const{getThumbProps:r,getInputProps:o,name:s}=vm(),a=bm(),c=r(t,n);return i.jsxs(Ie.div,{...c,className:ji("chakra-slider__thumb",t.className),__css:a.thumb,children:[c.children,s&&i.jsx("input",{...o({index:t.index})})]})});Hv.displayName="RangeSliderThumb";var A5=Te(function(t,n){const{getTrackProps:r}=vm(),o=bm(),s=r(t,n);return i.jsx(Ie.div,{...s,className:ji("chakra-slider__track",t.className),__css:o.track,"data-testid":"chakra-range-slider-track"})});A5.displayName="RangeSliderTrack";var N5=Te(function(t,n){const{getInnerTrackProps:r}=vm(),o=bm(),s=r(t,n);return i.jsx(Ie.div,{...s,className:"chakra-slider__filled-track",__css:o.filledTrack})});N5.displayName="RangeSliderFilledTrack";var kp=Te(function(t,n){const{getMarkerProps:r}=vm(),o=bm(),s=r(t,n);return i.jsx(Ie.div,{...s,className:ji("chakra-slider__marker",t.className),__css:o.mark})});kp.displayName="RangeSliderMark";function jB(e){var t;const{min:n=0,max:r=100,onChange:o,value:s,defaultValue:a,isReversed:c,direction:d="ltr",orientation:p="horizontal",id:h,isDisabled:m,isReadOnly:v,onChangeStart:b,onChangeEnd:w,step:y=1,getAriaValueText:S,"aria-valuetext":k,"aria-label":_,"aria-labelledby":I,name:P,focusThumbOnChange:E=!0,...O}=e,R=rr(b),M=rr(w),T=rr(S),A=I5({isReversed:c,direction:d,orientation:p}),[$,Q]=Ac({value:s,defaultValue:a??EB(n,r),onChange:o}),[B,V]=f.useState(!1),[q,G]=f.useState(!1),D=!(m||v),L=(r-n)/10,W=y||(r-n)/100,Y=rc($,n,r),ae=r-Y+n,ue=Bp(A?ae:Y,n,r),X=p==="vertical",K=R5({min:n,max:r,step:y,isDisabled:m,value:Y,isInteractive:D,isReversed:A,isVertical:X,eventSource:null,focusThumbOnChange:E,orientation:p}),U=f.useRef(null),se=f.useRef(null),re=f.useRef(null),oe=f.useId(),pe=h??oe,[le,ge]=[`slider-thumb-${pe}`,`slider-track-${pe}`],_e=f.useCallback(Ne=>{var qe,Pn;if(!U.current)return;const Pe=K.current;Pe.eventSource="pointer";const Je=U.current.getBoundingClientRect(),{clientX:Xe,clientY:dt}=(Pn=(qe=Ne.touches)==null?void 0:qe[0])!=null?Pn:Ne,Lt=X?Je.bottom-dt:Xe-Je.left,lr=X?Je.height:Je.width;let pn=Lt/lr;A&&(pn=1-pn);let ln=W3(pn,Pe.min,Pe.max);return Pe.step&&(ln=parseFloat(Iv(ln,Pe.min,Pe.step))),ln=rc(ln,Pe.min,Pe.max),ln},[X,A,K]),ie=f.useCallback(Ne=>{const qe=K.current;qe.isInteractive&&(Ne=parseFloat(Iv(Ne,qe.min,W)),Ne=rc(Ne,qe.min,qe.max),Q(Ne))},[W,Q,K]),Se=f.useMemo(()=>({stepUp(Ne=W){const qe=A?Y-Ne:Y+Ne;ie(qe)},stepDown(Ne=W){const qe=A?Y+Ne:Y-Ne;ie(qe)},reset(){ie(a||0)},stepTo(Ne){ie(Ne)}}),[ie,A,Y,W,a]),Fe=f.useCallback(Ne=>{const qe=K.current,Pe={ArrowRight:()=>Se.stepUp(),ArrowUp:()=>Se.stepUp(),ArrowLeft:()=>Se.stepDown(),ArrowDown:()=>Se.stepDown(),PageUp:()=>Se.stepUp(L),PageDown:()=>Se.stepDown(L),Home:()=>ie(qe.min),End:()=>ie(qe.max)}[Ne.key];Pe&&(Ne.preventDefault(),Ne.stopPropagation(),Pe(Ne),qe.eventSource="keyboard")},[Se,ie,L,K]),Ae=(t=T==null?void 0:T(Y))!=null?t:k,He=SB(se),{getThumbStyle:Ct,rootStyle:ct,trackStyle:on,innerTrackStyle:vt}=f.useMemo(()=>{const Ne=K.current,qe=He??{width:0,height:0};return j5({isReversed:A,orientation:Ne.orientation,thumbRects:[qe],thumbPercents:[ue]})},[A,He,ue,K]),bt=f.useCallback(()=>{K.current.focusThumbOnChange&&setTimeout(()=>{var qe;return(qe=se.current)==null?void 0:qe.focus()})},[K]);Ba(()=>{const Ne=K.current;bt(),Ne.eventSource==="keyboard"&&(M==null||M(Ne.value))},[Y,M]);function we(Ne){const qe=_e(Ne);qe!=null&&qe!==K.current.value&&Q(qe)}M5(re,{onPanSessionStart(Ne){const qe=K.current;qe.isInteractive&&(V(!0),bt(),we(Ne),R==null||R(qe.value))},onPanSessionEnd(){const Ne=K.current;Ne.isInteractive&&(V(!1),M==null||M(Ne.value))},onPan(Ne){K.current.isInteractive&&we(Ne)}});const Re=f.useCallback((Ne={},qe=null)=>({...Ne,...O,ref:cn(qe,re),tabIndex:-1,"aria-disabled":ic(m),"data-focused":Jo(q),style:{...Ne.style,...ct}}),[O,m,q,ct]),Pt=f.useCallback((Ne={},qe=null)=>({...Ne,ref:cn(qe,U),id:ge,"data-disabled":Jo(m),style:{...Ne.style,...on}}),[m,ge,on]),At=f.useCallback((Ne={},qe=null)=>({...Ne,ref:qe,style:{...Ne.style,...vt}}),[vt]),xe=f.useCallback((Ne={},qe=null)=>({...Ne,ref:cn(qe,se),role:"slider",tabIndex:D?0:void 0,id:le,"data-active":Jo(B),"aria-valuetext":Ae,"aria-valuemin":n,"aria-valuemax":r,"aria-valuenow":Y,"aria-orientation":p,"aria-disabled":ic(m),"aria-readonly":ic(v),"aria-label":_,"aria-labelledby":_?void 0:I,style:{...Ne.style,...Ct(0)},onKeyDown:lc(Ne.onKeyDown,Fe),onFocus:lc(Ne.onFocus,()=>G(!0)),onBlur:lc(Ne.onBlur,()=>G(!1))}),[D,le,B,Ae,n,r,Y,p,m,v,_,I,Ct,Fe]),ht=f.useCallback((Ne,qe=null)=>{const Pn=!(Ne.valuer),Pe=Y>=Ne.value,Je=Bp(Ne.value,n,r),Xe={position:"absolute",pointerEvents:"none",...IB({orientation:p,vertical:{bottom:A?`${100-Je}%`:`${Je}%`},horizontal:{left:A?`${100-Je}%`:`${Je}%`}})};return{...Ne,ref:qe,role:"presentation","aria-hidden":!0,"data-disabled":Jo(m),"data-invalid":Jo(!Pn),"data-highlighted":Jo(Pe),style:{...Ne.style,...Xe}}},[m,A,r,n,p,Y]),$t=f.useCallback((Ne={},qe=null)=>({...Ne,ref:qe,type:"hidden",value:Y,name:P}),[P,Y]);return{state:{value:Y,isFocused:q,isDragging:B},actions:Se,getRootProps:Re,getTrackProps:Pt,getInnerTrackProps:At,getThumbProps:xe,getMarkerProps:ht,getInputProps:$t}}function IB(e){const{orientation:t,vertical:n,horizontal:r}=e;return t==="vertical"?n:r}function EB(e,t){return t"}),[RB,xm]=Rn({name:"SliderStylesContext",hookName:"useSliderStyles",providerName:""}),$5=Te((e,t)=>{var n;const r={...e,orientation:(n=e==null?void 0:e.orientation)!=null?n:"horizontal"},o=Br("Slider",r),s=qn(r),{direction:a}=Mc();s.direction=a;const{getInputProps:c,getRootProps:d,...p}=jB(s),h=d(),m=c({},t);return i.jsx(OB,{value:p,children:i.jsx(RB,{value:o,children:i.jsxs(Ie.div,{...h,className:ji("chakra-slider",r.className),__css:o.container,children:[r.children,i.jsx("input",{...m})]})})})});$5.displayName="Slider";var z5=Te((e,t)=>{const{getThumbProps:n}=ym(),r=xm(),o=n(e,t);return i.jsx(Ie.div,{...o,className:ji("chakra-slider__thumb",e.className),__css:r.thumb})});z5.displayName="SliderThumb";var L5=Te((e,t)=>{const{getTrackProps:n}=ym(),r=xm(),o=n(e,t);return i.jsx(Ie.div,{...o,className:ji("chakra-slider__track",e.className),__css:r.track})});L5.displayName="SliderTrack";var B5=Te((e,t)=>{const{getInnerTrackProps:n}=ym(),r=xm(),o=n(e,t);return i.jsx(Ie.div,{...o,className:ji("chakra-slider__filled-track",e.className),__css:r.filledTrack})});B5.displayName="SliderFilledTrack";var Vl=Te((e,t)=>{const{getMarkerProps:n}=ym(),r=xm(),o=n(e,t);return i.jsx(Ie.div,{...o,className:ji("chakra-slider__marker",e.className),__css:r.mark})});Vl.displayName="SliderMark";var Nb=Te(function(t,n){const r=Br("Switch",t),{spacing:o="0.5rem",children:s,...a}=qn(t),{state:c,getInputProps:d,getCheckboxProps:p,getRootProps:h,getLabelProps:m}=F3(a),v=f.useMemo(()=>({display:"inline-block",position:"relative",verticalAlign:"middle",lineHeight:0,...r.container}),[r.container]),b=f.useMemo(()=>({display:"inline-flex",flexShrink:0,justifyContent:"flex-start",boxSizing:"content-box",cursor:"pointer",...r.track}),[r.track]),w=f.useMemo(()=>({userSelect:"none",marginStart:o,...r.label}),[o,r.label]);return i.jsxs(Ie.label,{...h(),className:kt("chakra-switch",t.className),__css:v,children:[i.jsx("input",{className:"chakra-switch__input",...d({},n)}),i.jsx(Ie.span,{...p(),className:"chakra-switch__track",__css:b,children:i.jsx(Ie.span,{__css:r.thumb,className:"chakra-switch__thumb","data-checked":tn(c.isChecked),"data-hover":tn(c.isHovered)})}),s&&i.jsx(Ie.span,{className:"chakra-switch__label",...m(),__css:w,children:s})]})});Nb.displayName="Switch";var[MB,DB,TB,AB]=X1();function NB(e){var t;const{defaultIndex:n,onChange:r,index:o,isManual:s,isLazy:a,lazyBehavior:c="unmount",orientation:d="horizontal",direction:p="ltr",...h}=e,[m,v]=f.useState(n??0),[b,w]=Ac({defaultValue:n??0,value:o,onChange:r});f.useEffect(()=>{o!=null&&v(o)},[o]);const y=TB(),S=f.useId();return{id:`tabs-${(t=e.id)!=null?t:S}`,selectedIndex:b,focusedIndex:m,setSelectedIndex:w,setFocusedIndex:v,isManual:s,isLazy:a,lazyBehavior:c,orientation:d,descendants:y,direction:p,htmlProps:h}}var[$B,wm]=Rn({name:"TabsContext",errorMessage:"useTabsContext: `context` is undefined. Seems you forgot to wrap all tabs components within "});function zB(e){const{focusedIndex:t,orientation:n,direction:r}=wm(),o=DB(),s=f.useCallback(a=>{const c=()=>{var _;const I=o.nextEnabled(t);I&&((_=I.node)==null||_.focus())},d=()=>{var _;const I=o.prevEnabled(t);I&&((_=I.node)==null||_.focus())},p=()=>{var _;const I=o.firstEnabled();I&&((_=I.node)==null||_.focus())},h=()=>{var _;const I=o.lastEnabled();I&&((_=I.node)==null||_.focus())},m=n==="horizontal",v=n==="vertical",b=a.key,w=r==="ltr"?"ArrowLeft":"ArrowRight",y=r==="ltr"?"ArrowRight":"ArrowLeft",k={[w]:()=>m&&d(),[y]:()=>m&&c(),ArrowDown:()=>v&&c(),ArrowUp:()=>v&&d(),Home:p,End:h}[b];k&&(a.preventDefault(),k(a))},[o,t,n,r]);return{...e,role:"tablist","aria-orientation":n,onKeyDown:et(e.onKeyDown,s)}}function LB(e){const{isDisabled:t,isFocusable:n,...r}=e,{setSelectedIndex:o,isManual:s,id:a,setFocusedIndex:c,selectedIndex:d}=wm(),{index:p,register:h}=AB({disabled:t&&!n}),m=p===d,v=()=>{o(p)},b=()=>{c(p),!s&&!(t&&n)&&o(p)},w=UP({...r,ref:cn(h,e.ref),isDisabled:t,isFocusable:n,onClick:et(e.onClick,v)}),y="button";return{...w,id:F5(a,p),role:"tab",tabIndex:m?0:-1,type:y,"aria-selected":m,"aria-controls":H5(a,p),onFocus:t?void 0:et(e.onFocus,b)}}var[BB,FB]=Rn({});function HB(e){const t=wm(),{id:n,selectedIndex:r}=t,s=gd(e.children).map((a,c)=>f.createElement(BB,{key:c,value:{isSelected:c===r,id:H5(n,c),tabId:F5(n,c),selectedIndex:r}},a));return{...e,children:s}}function WB(e){const{children:t,...n}=e,{isLazy:r,lazyBehavior:o}=wm(),{isSelected:s,id:a,tabId:c}=FB(),d=f.useRef(!1);s&&(d.current=!0);const p=Ib({wasSelected:d.current,isSelected:s,enabled:r,mode:o});return{tabIndex:0,...n,children:p?t:null,role:"tabpanel","aria-labelledby":c,hidden:!s,id:a}}function F5(e,t){return`${e}--tab-${t}`}function H5(e,t){return`${e}--tabpanel-${t}`}var[VB,Sm]=Rn({name:"TabsStylesContext",errorMessage:`useTabsStyles returned is 'undefined'. Seems you forgot to wrap the components in "" `}),Ed=Te(function(t,n){const r=Br("Tabs",t),{children:o,className:s,...a}=qn(t),{htmlProps:c,descendants:d,...p}=NB(a),h=f.useMemo(()=>p,[p]),{isFitted:m,...v}=c;return i.jsx(MB,{value:d,children:i.jsx($B,{value:h,children:i.jsx(VB,{value:r,children:i.jsx(Ie.div,{className:kt("chakra-tabs",s),ref:n,...v,__css:r.root,children:o})})})})});Ed.displayName="Tabs";var Od=Te(function(t,n){const r=zB({...t,ref:n}),s={display:"flex",...Sm().tablist};return i.jsx(Ie.div,{...r,className:kt("chakra-tabs__tablist",t.className),__css:s})});Od.displayName="TabList";var Cm=Te(function(t,n){const r=WB({...t,ref:n}),o=Sm();return i.jsx(Ie.div,{outline:"0",...r,className:kt("chakra-tabs__tab-panel",t.className),__css:o.tabpanel})});Cm.displayName="TabPanel";var km=Te(function(t,n){const r=HB(t),o=Sm();return i.jsx(Ie.div,{...r,width:"100%",ref:n,className:kt("chakra-tabs__tab-panels",t.className),__css:o.tabpanels})});km.displayName="TabPanels";var wc=Te(function(t,n){const r=Sm(),o=LB({...t,ref:n}),s={outline:"0",display:"flex",alignItems:"center",justifyContent:"center",...r.tab};return i.jsx(Ie.button,{...o,className:kt("chakra-tabs__tab",t.className),__css:s})});wc.displayName="Tab";function UB(e,t=[]){const n=Object.assign({},e);for(const r of t)r in n&&delete n[r];return n}var GB=["h","minH","height","minHeight"],W5=Te((e,t)=>{const n=$a("Textarea",e),{className:r,rows:o,...s}=qn(e),a=Z1(s),c=o?UB(n,GB):n;return i.jsx(Ie.textarea,{ref:t,rows:o,...a,className:kt("chakra-textarea",r),__css:c})});W5.displayName="Textarea";var qB={exit:{scale:.85,opacity:0,transition:{opacity:{duration:.15,easings:"easeInOut"},scale:{duration:.2,easings:"easeInOut"}}},enter:{scale:1,opacity:1,transition:{opacity:{easings:"easeOut",duration:.2},scale:{duration:.2,ease:[.175,.885,.4,1.1]}}}},Wv=e=>{var t;return((t=e.current)==null?void 0:t.ownerDocument)||document},_p=e=>{var t,n;return((n=(t=e.current)==null?void 0:t.ownerDocument)==null?void 0:n.defaultView)||window};function KB(e={}){const{openDelay:t=0,closeDelay:n=0,closeOnClick:r=!0,closeOnMouseDown:o,closeOnScroll:s,closeOnPointerDown:a=o,closeOnEsc:c=!0,onOpen:d,onClose:p,placement:h,id:m,isOpen:v,defaultIsOpen:b,arrowSize:w=10,arrowShadowColor:y,arrowPadding:S,modifiers:k,isDisabled:_,gutter:I,offset:P,direction:E,...O}=e,{isOpen:R,onOpen:M,onClose:T}=jb({isOpen:v,defaultIsOpen:b,onOpen:d,onClose:p}),{referenceRef:A,getPopperProps:$,getArrowInnerProps:Q,getArrowProps:B}=Pb({enabled:R,placement:h,arrowPadding:S,modifiers:k,gutter:I,offset:P,direction:E}),V=f.useId(),G=`tooltip-${m??V}`,D=f.useRef(null),L=f.useRef(),W=f.useCallback(()=>{L.current&&(clearTimeout(L.current),L.current=void 0)},[]),Y=f.useRef(),ae=f.useCallback(()=>{Y.current&&(clearTimeout(Y.current),Y.current=void 0)},[]),ye=f.useCallback(()=>{ae(),T()},[T,ae]),ue=YB(D,ye),X=f.useCallback(()=>{if(!_&&!L.current){ue();const ge=_p(D);L.current=ge.setTimeout(M,t)}},[ue,_,M,t]),K=f.useCallback(()=>{W();const ge=_p(D);Y.current=ge.setTimeout(ye,n)},[n,ye,W]),U=f.useCallback(()=>{R&&r&&K()},[r,K,R]),se=f.useCallback(()=>{R&&a&&K()},[a,K,R]),re=f.useCallback(ge=>{R&&ge.key==="Escape"&&K()},[R,K]);Yi(()=>Wv(D),"keydown",c?re:void 0),Yi(()=>{const ge=D.current;if(!ge)return null;const _e=DP(ge);return _e.localName==="body"?_p(D):_e},"scroll",()=>{R&&s&&ye()},{passive:!0,capture:!0}),f.useEffect(()=>{_&&(W(),R&&T())},[_,R,T,W]),f.useEffect(()=>()=>{W(),ae()},[W,ae]),Yi(()=>D.current,"pointerleave",K);const oe=f.useCallback((ge={},_e=null)=>({...ge,ref:cn(D,_e,A),onPointerEnter:et(ge.onPointerEnter,Se=>{Se.pointerType!=="touch"&&X()}),onClick:et(ge.onClick,U),onPointerDown:et(ge.onPointerDown,se),onFocus:et(ge.onFocus,X),onBlur:et(ge.onBlur,K),"aria-describedby":R?G:void 0}),[X,K,se,R,G,U,A]),pe=f.useCallback((ge={},_e=null)=>$({...ge,style:{...ge.style,[Pr.arrowSize.var]:w?`${w}px`:void 0,[Pr.arrowShadowColor.var]:y}},_e),[$,w,y]),le=f.useCallback((ge={},_e=null)=>{const ie={...ge.style,position:"relative",transformOrigin:Pr.transformOrigin.varRef};return{ref:_e,...O,...ge,id:G,role:"tooltip",style:ie}},[O,G]);return{isOpen:R,show:X,hide:K,getTriggerProps:oe,getTooltipProps:le,getTooltipPositionerProps:pe,getArrowProps:B,getArrowInnerProps:Q}}var j0="chakra-ui:close-tooltip";function YB(e,t){return f.useEffect(()=>{const n=Wv(e);return n.addEventListener(j0,t),()=>n.removeEventListener(j0,t)},[t,e]),()=>{const n=Wv(e),r=_p(e);n.dispatchEvent(new r.CustomEvent(j0))}}function XB(e,t=[]){const n=Object.assign({},e);for(const r of t)r in n&&delete n[r];return n}function QB(e,t){const n={};for(const r of t)r in e&&(n[r]=e[r]);return n}var JB=Ie(Xr.div),wn=Te((e,t)=>{var n,r;const o=$a("Tooltip",e),s=qn(e),a=Mc(),{children:c,label:d,shouldWrapChildren:p,"aria-label":h,hasArrow:m,bg:v,portalProps:b,background:w,backgroundColor:y,bgColor:S,motionProps:k,..._}=s,I=(r=(n=w??y)!=null?n:v)!=null?r:S;if(I){o.bg=I;const $=CR(a,"colors",I);o[Pr.arrowBg.var]=$}const P=KB({..._,direction:a.direction}),E=typeof c=="string"||p;let O;if(E)O=i.jsx(Ie.span,{display:"inline-block",tabIndex:0,...P.getTriggerProps(),children:c});else{const $=f.Children.only(c);O=f.cloneElement($,P.getTriggerProps($.props,$.ref))}const R=!!h,M=P.getTooltipProps({},t),T=R?XB(M,["role","id"]):M,A=QB(M,["role","id"]);return d?i.jsxs(i.Fragment,{children:[O,i.jsx(Fo,{children:P.isOpen&&i.jsx(Vu,{...b,children:i.jsx(Ie.div,{...P.getTooltipPositionerProps(),__css:{zIndex:o.zIndex,pointerEvents:"none"},children:i.jsxs(JB,{variants:qB,initial:"exit",animate:"enter",exit:"exit",...k,...T,__css:o,children:[d,R&&i.jsx(Ie.span,{srOnly:!0,...A,children:h}),m&&i.jsx(Ie.div,{"data-popper-arrow":!0,className:"chakra-tooltip__arrow-wrapper",children:i.jsx(Ie.div,{"data-popper-arrow-inner":!0,className:"chakra-tooltip__arrow",__css:{bg:o.bg}})})]})})})})]}):i.jsx(i.Fragment,{children:c})});wn.displayName="Tooltip";function ZB(e,t={}){let n=f.useCallback(o=>t.keys?fT(e,t.keys,o):e.listen(o),[t.keys,e]),r=e.get.bind(e);return f.useSyncExternalStore(n,r,r)}const mo=e=>e.system,eF=e=>e.system.toastQueue,V5=fe(mo,e=>e.language,Ge),jr=fe(e=>e,e=>e.system.isProcessing||!e.system.isConnected),tF=fe(mo,e=>{const{consoleLogLevel:t,shouldLogToConsole:n}=e;return{consoleLogLevel:t,shouldLogToConsole:n}},{memoizeOptions:{resultEqualityCheck:Qt}}),nF=()=>{const{consoleLogLevel:e,shouldLogToConsole:t}=z(tF);return f.useEffect(()=>{t?(localStorage.setItem("ROARR_LOG","true"),localStorage.setItem("ROARR_FILTER",`context.logLevel:>=${kR[e]}`)):localStorage.setItem("ROARR_LOG","false"),I2.ROARR.write=_R.createLogWriter()},[e,t]),f.useEffect(()=>{const r={...PR};E2.set(I2.Roarr.child(r))},[]),ZB(E2)},rF=()=>{const e=te(),t=z(eF),n=BT();return f.useEffect(()=>{t.forEach(r=>{n(r)}),t.length>0&&e(jR())},[e,n,t]),null},Bc=()=>{const e=te();return f.useCallback(n=>e(Dn(Bn(n))),[e])};var oF=new Map([["aac","audio/aac"],["abw","application/x-abiword"],["arc","application/x-freearc"],["avif","image/avif"],["avi","video/x-msvideo"],["azw","application/vnd.amazon.ebook"],["bin","application/octet-stream"],["bmp","image/bmp"],["bz","application/x-bzip"],["bz2","application/x-bzip2"],["cda","application/x-cdf"],["csh","application/x-csh"],["css","text/css"],["csv","text/csv"],["doc","application/msword"],["docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],["eot","application/vnd.ms-fontobject"],["epub","application/epub+zip"],["gz","application/gzip"],["gif","image/gif"],["heic","image/heic"],["heif","image/heif"],["htm","text/html"],["html","text/html"],["ico","image/vnd.microsoft.icon"],["ics","text/calendar"],["jar","application/java-archive"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["js","text/javascript"],["json","application/json"],["jsonld","application/ld+json"],["mid","audio/midi"],["midi","audio/midi"],["mjs","text/javascript"],["mp3","audio/mpeg"],["mp4","video/mp4"],["mpeg","video/mpeg"],["mpkg","application/vnd.apple.installer+xml"],["odp","application/vnd.oasis.opendocument.presentation"],["ods","application/vnd.oasis.opendocument.spreadsheet"],["odt","application/vnd.oasis.opendocument.text"],["oga","audio/ogg"],["ogv","video/ogg"],["ogx","application/ogg"],["opus","audio/opus"],["otf","font/otf"],["png","image/png"],["pdf","application/pdf"],["php","application/x-httpd-php"],["ppt","application/vnd.ms-powerpoint"],["pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],["rar","application/vnd.rar"],["rtf","application/rtf"],["sh","application/x-sh"],["svg","image/svg+xml"],["swf","application/x-shockwave-flash"],["tar","application/x-tar"],["tif","image/tiff"],["tiff","image/tiff"],["ts","video/mp2t"],["ttf","font/ttf"],["txt","text/plain"],["vsd","application/vnd.visio"],["wav","audio/wav"],["weba","audio/webm"],["webm","video/webm"],["webp","image/webp"],["woff","font/woff"],["woff2","font/woff2"],["xhtml","application/xhtml+xml"],["xls","application/vnd.ms-excel"],["xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],["xml","application/xml"],["xul","application/vnd.mozilla.xul+xml"],["zip","application/zip"],["7z","application/x-7z-compressed"],["mkv","video/x-matroska"],["mov","video/quicktime"],["msg","application/vnd.ms-outlook"]]);function Rd(e,t){var n=sF(e);if(typeof n.path!="string"){var r=e.webkitRelativePath;Object.defineProperty(n,"path",{value:typeof t=="string"?t:typeof r=="string"&&r.length>0?r:e.name,writable:!1,configurable:!1,enumerable:!0})}return n}function sF(e){var t=e.name,n=t&&t.lastIndexOf(".")!==-1;if(n&&!e.type){var r=t.split(".").pop().toLowerCase(),o=oF.get(r);o&&Object.defineProperty(e,"type",{value:o,writable:!1,configurable:!1,enumerable:!0})}return e}var aF=[".DS_Store","Thumbs.db"];function iF(e){return Nc(this,void 0,void 0,function(){return $c(this,function(t){return qp(e)&&lF(e.dataTransfer)?[2,fF(e.dataTransfer,e.type)]:cF(e)?[2,uF(e)]:Array.isArray(e)&&e.every(function(n){return"getFile"in n&&typeof n.getFile=="function"})?[2,dF(e)]:[2,[]]})})}function lF(e){return qp(e)}function cF(e){return qp(e)&&qp(e.target)}function qp(e){return typeof e=="object"&&e!==null}function uF(e){return Vv(e.target.files).map(function(t){return Rd(t)})}function dF(e){return Nc(this,void 0,void 0,function(){var t;return $c(this,function(n){switch(n.label){case 0:return[4,Promise.all(e.map(function(r){return r.getFile()}))];case 1:return t=n.sent(),[2,t.map(function(r){return Rd(r)})]}})})}function fF(e,t){return Nc(this,void 0,void 0,function(){var n,r;return $c(this,function(o){switch(o.label){case 0:return e.items?(n=Vv(e.items).filter(function(s){return s.kind==="file"}),t!=="drop"?[2,n]:[4,Promise.all(n.map(pF))]):[3,2];case 1:return r=o.sent(),[2,aS(U5(r))];case 2:return[2,aS(Vv(e.files).map(function(s){return Rd(s)}))]}})})}function aS(e){return e.filter(function(t){return aF.indexOf(t.name)===-1})}function Vv(e){if(e===null)return[];for(var t=[],n=0;ne.length)&&(t=e.length);for(var n=0,r=new Array(t);nn)return[!1,dS(n)];if(e.sizen)return[!1,dS(n)]}return[!0,null]}function Vi(e){return e!=null}function EF(e){var t=e.files,n=e.accept,r=e.minSize,o=e.maxSize,s=e.multiple,a=e.maxFiles,c=e.validator;return!s&&t.length>1||s&&a>=1&&t.length>a?!1:t.every(function(d){var p=Y5(d,n),h=Zu(p,1),m=h[0],v=X5(d,r,o),b=Zu(v,1),w=b[0],y=c?c(d):null;return m&&w&&!y})}function Kp(e){return typeof e.isPropagationStopped=="function"?e.isPropagationStopped():typeof e.cancelBubble<"u"?e.cancelBubble:!1}function zf(e){return e.dataTransfer?Array.prototype.some.call(e.dataTransfer.types,function(t){return t==="Files"||t==="application/x-moz-file"}):!!e.target&&!!e.target.files}function pS(e){e.preventDefault()}function OF(e){return e.indexOf("MSIE")!==-1||e.indexOf("Trident/")!==-1}function RF(e){return e.indexOf("Edge/")!==-1}function MF(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return OF(e)||RF(e)}function Gs(){for(var e=arguments.length,t=new Array(e),n=0;n1?o-1:0),a=1;ae.length)&&(t=e.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function YF(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,s;for(s=0;s=0)&&(n[o]=e[o]);return n}var $b=f.forwardRef(function(e,t){var n=e.children,r=Yp(e,zF),o=zb(r),s=o.open,a=Yp(o,LF);return f.useImperativeHandle(t,function(){return{open:s}},[s]),F.createElement(f.Fragment,null,n(dr(dr({},a),{},{open:s})))});$b.displayName="Dropzone";var e6={disabled:!1,getFilesFromEvent:iF,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!0,autoFocus:!1};$b.defaultProps=e6;$b.propTypes={children:zn.func,accept:zn.objectOf(zn.arrayOf(zn.string)),multiple:zn.bool,preventDropOnDocument:zn.bool,noClick:zn.bool,noKeyboard:zn.bool,noDrag:zn.bool,noDragEventsBubbling:zn.bool,minSize:zn.number,maxSize:zn.number,maxFiles:zn.number,disabled:zn.bool,getFilesFromEvent:zn.func,onFileDialogCancel:zn.func,onFileDialogOpen:zn.func,useFsAccessApi:zn.bool,autoFocus:zn.bool,onDragEnter:zn.func,onDragLeave:zn.func,onDragOver:zn.func,onDrop:zn.func,onDropAccepted:zn.func,onDropRejected:zn.func,onError:zn.func,validator:zn.func};var Kv={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function zb(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=dr(dr({},e6),e),n=t.accept,r=t.disabled,o=t.getFilesFromEvent,s=t.maxSize,a=t.minSize,c=t.multiple,d=t.maxFiles,p=t.onDragEnter,h=t.onDragLeave,m=t.onDragOver,v=t.onDrop,b=t.onDropAccepted,w=t.onDropRejected,y=t.onFileDialogCancel,S=t.onFileDialogOpen,k=t.useFsAccessApi,_=t.autoFocus,I=t.preventDropOnDocument,P=t.noClick,E=t.noKeyboard,O=t.noDrag,R=t.noDragEventsBubbling,M=t.onError,T=t.validator,A=f.useMemo(function(){return AF(n)},[n]),$=f.useMemo(function(){return TF(n)},[n]),Q=f.useMemo(function(){return typeof S=="function"?S:mS},[S]),B=f.useMemo(function(){return typeof y=="function"?y:mS},[y]),V=f.useRef(null),q=f.useRef(null),G=f.useReducer(XF,Kv),D=I0(G,2),L=D[0],W=D[1],Y=L.isFocused,ae=L.isFileDialogActive,ye=f.useRef(typeof window<"u"&&window.isSecureContext&&k&&DF()),ue=function(){!ye.current&&ae&&setTimeout(function(){if(q.current){var Re=q.current.files;Re.length||(W({type:"closeDialog"}),B())}},300)};f.useEffect(function(){return window.addEventListener("focus",ue,!1),function(){window.removeEventListener("focus",ue,!1)}},[q,ae,B,ye]);var X=f.useRef([]),K=function(Re){V.current&&V.current.contains(Re.target)||(Re.preventDefault(),X.current=[])};f.useEffect(function(){return I&&(document.addEventListener("dragover",pS,!1),document.addEventListener("drop",K,!1)),function(){I&&(document.removeEventListener("dragover",pS),document.removeEventListener("drop",K))}},[V,I]),f.useEffect(function(){return!r&&_&&V.current&&V.current.focus(),function(){}},[V,_,r]);var U=f.useCallback(function(we){M?M(we):console.error(we)},[M]),se=f.useCallback(function(we){we.preventDefault(),we.persist(),ct(we),X.current=[].concat(HF(X.current),[we.target]),zf(we)&&Promise.resolve(o(we)).then(function(Re){if(!(Kp(we)&&!R)){var Pt=Re.length,At=Pt>0&&EF({files:Re,accept:A,minSize:a,maxSize:s,multiple:c,maxFiles:d,validator:T}),xe=Pt>0&&!At;W({isDragAccept:At,isDragReject:xe,isDragActive:!0,type:"setDraggedFiles"}),p&&p(we)}}).catch(function(Re){return U(Re)})},[o,p,U,R,A,a,s,c,d,T]),re=f.useCallback(function(we){we.preventDefault(),we.persist(),ct(we);var Re=zf(we);if(Re&&we.dataTransfer)try{we.dataTransfer.dropEffect="copy"}catch{}return Re&&m&&m(we),!1},[m,R]),oe=f.useCallback(function(we){we.preventDefault(),we.persist(),ct(we);var Re=X.current.filter(function(At){return V.current&&V.current.contains(At)}),Pt=Re.indexOf(we.target);Pt!==-1&&Re.splice(Pt,1),X.current=Re,!(Re.length>0)&&(W({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),zf(we)&&h&&h(we))},[V,h,R]),pe=f.useCallback(function(we,Re){var Pt=[],At=[];we.forEach(function(xe){var ht=Y5(xe,A),$t=I0(ht,2),zt=$t[0],Ne=$t[1],qe=X5(xe,a,s),Pn=I0(qe,2),Pe=Pn[0],Je=Pn[1],Xe=T?T(xe):null;if(zt&&Pe&&!Xe)Pt.push(xe);else{var dt=[Ne,Je];Xe&&(dt=dt.concat(Xe)),At.push({file:xe,errors:dt.filter(function(Lt){return Lt})})}}),(!c&&Pt.length>1||c&&d>=1&&Pt.length>d)&&(Pt.forEach(function(xe){At.push({file:xe,errors:[IF]})}),Pt.splice(0)),W({acceptedFiles:Pt,fileRejections:At,type:"setFiles"}),v&&v(Pt,At,Re),At.length>0&&w&&w(At,Re),Pt.length>0&&b&&b(Pt,Re)},[W,c,A,a,s,d,v,b,w,T]),le=f.useCallback(function(we){we.preventDefault(),we.persist(),ct(we),X.current=[],zf(we)&&Promise.resolve(o(we)).then(function(Re){Kp(we)&&!R||pe(Re,we)}).catch(function(Re){return U(Re)}),W({type:"reset"})},[o,pe,U,R]),ge=f.useCallback(function(){if(ye.current){W({type:"openDialog"}),Q();var we={multiple:c,types:$};window.showOpenFilePicker(we).then(function(Re){return o(Re)}).then(function(Re){pe(Re,null),W({type:"closeDialog"})}).catch(function(Re){NF(Re)?(B(Re),W({type:"closeDialog"})):$F(Re)?(ye.current=!1,q.current?(q.current.value=null,q.current.click()):U(new Error("Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no was provided."))):U(Re)});return}q.current&&(W({type:"openDialog"}),Q(),q.current.value=null,q.current.click())},[W,Q,B,k,pe,U,$,c]),_e=f.useCallback(function(we){!V.current||!V.current.isEqualNode(we.target)||(we.key===" "||we.key==="Enter"||we.keyCode===32||we.keyCode===13)&&(we.preventDefault(),ge())},[V,ge]),ie=f.useCallback(function(){W({type:"focus"})},[]),Se=f.useCallback(function(){W({type:"blur"})},[]),Fe=f.useCallback(function(){P||(MF()?setTimeout(ge,0):ge())},[P,ge]),Ae=function(Re){return r?null:Re},He=function(Re){return E?null:Ae(Re)},Ct=function(Re){return O?null:Ae(Re)},ct=function(Re){R&&Re.stopPropagation()},on=f.useMemo(function(){return function(){var we=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},Re=we.refKey,Pt=Re===void 0?"ref":Re,At=we.role,xe=we.onKeyDown,ht=we.onFocus,$t=we.onBlur,zt=we.onClick,Ne=we.onDragEnter,qe=we.onDragOver,Pn=we.onDragLeave,Pe=we.onDrop,Je=Yp(we,BF);return dr(dr(qv({onKeyDown:He(Gs(xe,_e)),onFocus:He(Gs(ht,ie)),onBlur:He(Gs($t,Se)),onClick:Ae(Gs(zt,Fe)),onDragEnter:Ct(Gs(Ne,se)),onDragOver:Ct(Gs(qe,re)),onDragLeave:Ct(Gs(Pn,oe)),onDrop:Ct(Gs(Pe,le)),role:typeof At=="string"&&At!==""?At:"presentation"},Pt,V),!r&&!E?{tabIndex:0}:{}),Je)}},[V,_e,ie,Se,Fe,se,re,oe,le,E,O,r]),vt=f.useCallback(function(we){we.stopPropagation()},[]),bt=f.useMemo(function(){return function(){var we=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},Re=we.refKey,Pt=Re===void 0?"ref":Re,At=we.onChange,xe=we.onClick,ht=Yp(we,FF),$t=qv({accept:A,multiple:c,type:"file",style:{display:"none"},onChange:Ae(Gs(At,le)),onClick:Ae(Gs(xe,vt)),tabIndex:-1},Pt,q);return dr(dr({},$t),ht)}},[q,n,c,le,r]);return dr(dr({},L),{},{isFocused:Y&&!r,getRootProps:on,getInputProps:bt,rootRef:V,inputRef:q,open:Ae(ge)})}function XF(e,t){switch(t.type){case"focus":return dr(dr({},e),{},{isFocused:!0});case"blur":return dr(dr({},e),{},{isFocused:!1});case"openDialog":return dr(dr({},Kv),{},{isFileDialogActive:!0});case"closeDialog":return dr(dr({},e),{},{isFileDialogActive:!1});case"setDraggedFiles":return dr(dr({},e),{},{isDragActive:t.isDragActive,isDragAccept:t.isDragAccept,isDragReject:t.isDragReject});case"setFiles":return dr(dr({},e),{},{acceptedFiles:t.acceptedFiles,fileRejections:t.fileRejections});case"reset":return dr({},Kv);default:return e}}function mS(){}function Yv(){return Yv=Object.assign?Object.assign.bind():function(e){for(var t=1;t'),!0):t?e.some(function(n){return t.includes(n)})||e.includes("*"):!0}var rH=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,s=n.meta,a=n.mod,c=n.shift,d=n.ctrl,p=n.keys,h=t.key,m=t.code,v=t.ctrlKey,b=t.metaKey,w=t.shiftKey,y=t.altKey,S=ii(m),k=h.toLowerCase();if(!r){if(o===!y&&k!=="alt"||c===!w&&k!=="shift")return!1;if(a){if(!b&&!v)return!1}else if(s===!b&&k!=="meta"&&k!=="os"||d===!v&&k!=="ctrl"&&k!=="control")return!1}return p&&p.length===1&&(p.includes(k)||p.includes(S))?!0:p?n6(p):!p},oH=f.createContext(void 0),sH=function(){return f.useContext(oH)};function a6(e,t){return e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(e).length===Object.keys(t).length&&Object.keys(e).reduce(function(n,r){return n&&a6(e[r],t[r])},!0):e===t}var aH=f.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),iH=function(){return f.useContext(aH)};function lH(e){var t=f.useRef(void 0);return a6(t.current,e)||(t.current=e),t.current}var gS=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},cH=typeof window<"u"?f.useLayoutEffect:f.useEffect;function nt(e,t,n,r){var o=f.useRef(null),s=f.useRef(!1),a=n instanceof Array?r instanceof Array?void 0:r:n,c=e instanceof Array?e.join(a==null?void 0:a.splitKey):e,d=n instanceof Array?n:r instanceof Array?r:void 0,p=f.useCallback(t,d??[]),h=f.useRef(p);d?h.current=p:h.current=t;var m=lH(a),v=iH(),b=v.enabledScopes,w=sH();return cH(function(){if(!((m==null?void 0:m.enabled)===!1||!nH(b,m==null?void 0:m.scopes))){var y=function(P,E){var O;if(E===void 0&&(E=!1),!(tH(P)&&!s6(P,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(P))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){gS(P);return}(O=P.target)!=null&&O.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||E0(c,m==null?void 0:m.splitKey).forEach(function(R){var M,T=O0(R,m==null?void 0:m.combinationKey);if(rH(P,T,m==null?void 0:m.ignoreModifiers)||(M=T.keys)!=null&&M.includes("*")){if(E&&s.current)return;if(ZF(P,T,m==null?void 0:m.preventDefault),!eH(P,T,m==null?void 0:m.enabled)){gS(P);return}h.current(P,T),E||(s.current=!0)}})}},S=function(P){P.key!==void 0&&(r6(ii(P.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&y(P))},k=function(P){P.key!==void 0&&(o6(ii(P.code)),s.current=!1,m!=null&&m.keyup&&y(P,!0))},_=o.current||(a==null?void 0:a.document)||document;return _.addEventListener("keyup",k),_.addEventListener("keydown",S),w&&E0(c,m==null?void 0:m.splitKey).forEach(function(I){return w.addHotkey(O0(I,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){_.removeEventListener("keyup",k),_.removeEventListener("keydown",S),w&&E0(c,m==null?void 0:m.splitKey).forEach(function(I){return w.removeHotkey(O0(I,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[c,m,b]),o}const uH=e=>{const{isDragAccept:t,isDragReject:n,setIsHandlingUpload:r}=e;return nt("esc",()=>{r(!1)}),i.jsxs(Oe,{sx:{position:"absolute",top:0,insetInlineStart:0,width:"100vw",height:"100vh",zIndex:999,backdropFilter:"blur(20px)"},children:[i.jsx(H,{sx:{position:"absolute",top:0,insetInlineStart:0,w:"full",h:"full",bg:"base.700",_dark:{bg:"base.900"},opacity:.7,alignItems:"center",justifyContent:"center",transitionProperty:"common",transitionDuration:"0.1s"}}),i.jsx(H,{sx:{position:"absolute",top:0,insetInlineStart:0,width:"full",height:"full",alignItems:"center",justifyContent:"center",p:4},children:i.jsx(H,{sx:{width:"full",height:"full",alignItems:"center",justifyContent:"center",flexDir:"column",gap:4,borderWidth:3,borderRadius:"xl",borderStyle:"dashed",color:"base.100",borderColor:"base.100",_dark:{borderColor:"base.200"}},children:t?i.jsx(Xs,{size:"lg",children:"Drop to Upload"}):i.jsxs(i.Fragment,{children:[i.jsx(Xs,{size:"lg",children:"Invalid Upload"}),i.jsx(Xs,{size:"md",children:"Must be single JPEG or PNG image"})]})})})]})},dH=fe([Ye,Kn],({gallery:e},t)=>{let n={type:"TOAST"};t==="unifiedCanvas"&&(n={type:"SET_CANVAS_INITIAL_IMAGE"}),t==="img2img"&&(n={type:"SET_INITIAL_IMAGE"});const{autoAddBoardId:r}=e;return{autoAddBoardId:r,postUploadAction:n}},Ge),fH=e=>{const{children:t}=e,{autoAddBoardId:n,postUploadAction:r}=z(dH),o=z(jr),s=Bc(),{t:a}=be(),[c,d]=f.useState(!1),[p]=j_(),h=f.useCallback(I=>{d(!0),s({title:a("toast.uploadFailed"),description:I.errors.map(P=>P.message).join(` +`),status:"error"})},[a,s]),m=f.useCallback(async I=>{p({file:I,image_category:"user",is_intermediate:!1,postUploadAction:r,board_id:n})},[n,r,p]),v=f.useCallback((I,P)=>{if(P.length>1){s({title:a("toast.uploadFailed"),description:a("toast.uploadFailedInvalidUploadDesc"),status:"error"});return}P.forEach(E=>{h(E)}),I.forEach(E=>{m(E)})},[a,s,m,h]),{getRootProps:b,getInputProps:w,isDragAccept:y,isDragReject:S,isDragActive:k,inputRef:_}=zb({accept:{"image/png":[".png"],"image/jpeg":[".jpg",".jpeg",".png"]},noClick:!0,onDrop:v,onDragOver:()=>d(!0),disabled:o,multiple:!1});return f.useEffect(()=>{const I=async P=>{var E,O;_.current&&(E=P.clipboardData)!=null&&E.files&&(_.current.files=P.clipboardData.files,(O=_.current)==null||O.dispatchEvent(new Event("change",{bubbles:!0})))};return document.addEventListener("paste",I),()=>{document.removeEventListener("paste",I)}},[_]),i.jsxs(Oe,{...b({style:{}}),onKeyDown:I=>{I.key},children:[i.jsx("input",{...w()}),t,i.jsx(Fo,{children:k&&c&&i.jsx(Xr.div,{initial:{opacity:0},animate:{opacity:1,transition:{duration:.1}},exit:{opacity:0,transition:{duration:.1}},children:i.jsx(uH,{isDragAccept:y,isDragReject:S,setIsHandlingUpload:d})},"image-upload-overlay")})]})},pH=f.memo(fH),mn=e=>e.canvas,ir=fe([mn,Kn,mo],(e,t,n)=>e.layerState.stagingArea.images.length>0||t==="unifiedCanvas"&&n.isProcessing),hH=e=>e.canvas.layerState.objects.find(I_),mH=UD(e=>{e(E_(!0))},300),So=()=>(e,t)=>{Kn(t())==="unifiedCanvas"&&mH(e)};var gH=globalThis&&globalThis.__extends||function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(r[s]=o[s])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}(),kr=globalThis&&globalThis.__assign||function(){return kr=Object.assign||function(e){for(var t,n=1,r=arguments.length;n"u"?void 0:Number(r),maxHeight:typeof o>"u"?void 0:Number(o),minWidth:typeof s>"u"?void 0:Number(s),minHeight:typeof a>"u"?void 0:Number(a)}},CH=["as","style","className","grid","snap","bounds","boundsByDirection","size","defaultSize","minWidth","minHeight","maxWidth","maxHeight","lockAspectRatio","lockAspectRatioExtraWidth","lockAspectRatioExtraHeight","enable","handleStyles","handleClasses","handleWrapperStyle","handleWrapperClass","children","onResizeStart","onResize","onResizeStop","handleComponent","scale","resizeRatio","snapGap"],wS="__resizable_base__",kH=function(e){yH(t,e);function t(n){var r=e.call(this,n)||this;return r.ratio=1,r.resizable=null,r.parentLeft=0,r.parentTop=0,r.resizableLeft=0,r.resizableRight=0,r.resizableTop=0,r.resizableBottom=0,r.targetLeft=0,r.targetTop=0,r.appendBase=function(){if(!r.resizable||!r.window)return null;var o=r.parentNode;if(!o)return null;var s=r.window.document.createElement("div");return s.style.width="100%",s.style.height="100%",s.style.position="absolute",s.style.transform="scale(0, 0)",s.style.left="0",s.style.flex="0 0 100%",s.classList?s.classList.add(wS):s.className+=wS,o.appendChild(s),s},r.removeBase=function(o){var s=r.parentNode;s&&s.removeChild(o)},r.ref=function(o){o&&(r.resizable=o)},r.state={isResizing:!1,width:typeof(r.propsSize&&r.propsSize.width)>"u"?"auto":r.propsSize&&r.propsSize.width,height:typeof(r.propsSize&&r.propsSize.height)>"u"?"auto":r.propsSize&&r.propsSize.height,direction:"right",original:{x:0,y:0,width:0,height:0},backgroundStyle:{height:"100%",width:"100%",backgroundColor:"rgba(0,0,0,0)",cursor:"auto",opacity:0,position:"fixed",zIndex:9999,top:"0",left:"0",bottom:"0",right:"0"},flexBasis:void 0},r.onResizeStart=r.onResizeStart.bind(r),r.onMouseMove=r.onMouseMove.bind(r),r.onMouseUp=r.onMouseUp.bind(r),r}return Object.defineProperty(t.prototype,"parentNode",{get:function(){return this.resizable?this.resizable.parentNode:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"window",{get:function(){return!this.resizable||!this.resizable.ownerDocument?null:this.resizable.ownerDocument.defaultView},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"propsSize",{get:function(){return this.props.size||this.props.defaultSize||xH},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"size",{get:function(){var n=0,r=0;if(this.resizable&&this.window){var o=this.resizable.offsetWidth,s=this.resizable.offsetHeight,a=this.resizable.style.position;a!=="relative"&&(this.resizable.style.position="relative"),n=this.resizable.style.width!=="auto"?this.resizable.offsetWidth:o,r=this.resizable.style.height!=="auto"?this.resizable.offsetHeight:s,this.resizable.style.position=a}return{width:n,height:r}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sizeStyle",{get:function(){var n=this,r=this.props.size,o=function(c){if(typeof n.state[c]>"u"||n.state[c]==="auto")return"auto";if(n.propsSize&&n.propsSize[c]&&n.propsSize[c].toString().endsWith("%")){if(n.state[c].toString().endsWith("%"))return n.state[c].toString();var d=n.getParentSize(),p=Number(n.state[c].toString().replace("px","")),h=p/d[c]*100;return h+"%"}return R0(n.state[c])},s=r&&typeof r.width<"u"&&!this.state.isResizing?R0(r.width):o("width"),a=r&&typeof r.height<"u"&&!this.state.isResizing?R0(r.height):o("height");return{width:s,height:a}},enumerable:!1,configurable:!0}),t.prototype.getParentSize=function(){if(!this.parentNode)return this.window?{width:this.window.innerWidth,height:this.window.innerHeight}:{width:0,height:0};var n=this.appendBase();if(!n)return{width:0,height:0};var r=!1,o=this.parentNode.style.flexWrap;o!=="wrap"&&(r=!0,this.parentNode.style.flexWrap="wrap"),n.style.position="relative",n.style.minWidth="100%",n.style.minHeight="100%";var s={width:n.offsetWidth,height:n.offsetHeight};return r&&(this.parentNode.style.flexWrap=o),this.removeBase(n),s},t.prototype.bindEvents=function(){this.window&&(this.window.addEventListener("mouseup",this.onMouseUp),this.window.addEventListener("mousemove",this.onMouseMove),this.window.addEventListener("mouseleave",this.onMouseUp),this.window.addEventListener("touchmove",this.onMouseMove,{capture:!0,passive:!1}),this.window.addEventListener("touchend",this.onMouseUp))},t.prototype.unbindEvents=function(){this.window&&(this.window.removeEventListener("mouseup",this.onMouseUp),this.window.removeEventListener("mousemove",this.onMouseMove),this.window.removeEventListener("mouseleave",this.onMouseUp),this.window.removeEventListener("touchmove",this.onMouseMove,!0),this.window.removeEventListener("touchend",this.onMouseUp))},t.prototype.componentDidMount=function(){if(!(!this.resizable||!this.window)){var n=this.window.getComputedStyle(this.resizable);this.setState({width:this.state.width||this.size.width,height:this.state.height||this.size.height,flexBasis:n.flexBasis!=="auto"?n.flexBasis:void 0})}},t.prototype.componentWillUnmount=function(){this.window&&this.unbindEvents()},t.prototype.createSizeForCssProperty=function(n,r){var o=this.propsSize&&this.propsSize[r];return this.state[r]==="auto"&&this.state.original[r]===n&&(typeof o>"u"||o==="auto")?"auto":n},t.prototype.calculateNewMaxFromBoundary=function(n,r){var o=this.props.boundsByDirection,s=this.state.direction,a=o&&Ll("left",s),c=o&&Ll("top",s),d,p;if(this.props.bounds==="parent"){var h=this.parentNode;h&&(d=a?this.resizableRight-this.parentLeft:h.offsetWidth+(this.parentLeft-this.resizableLeft),p=c?this.resizableBottom-this.parentTop:h.offsetHeight+(this.parentTop-this.resizableTop))}else this.props.bounds==="window"?this.window&&(d=a?this.resizableRight:this.window.innerWidth-this.resizableLeft,p=c?this.resizableBottom:this.window.innerHeight-this.resizableTop):this.props.bounds&&(d=a?this.resizableRight-this.targetLeft:this.props.bounds.offsetWidth+(this.targetLeft-this.resizableLeft),p=c?this.resizableBottom-this.targetTop:this.props.bounds.offsetHeight+(this.targetTop-this.resizableTop));return d&&Number.isFinite(d)&&(n=n&&n"u"?10:s.width,m=typeof o.width>"u"||o.width<0?n:o.width,v=typeof s.height>"u"?10:s.height,b=typeof o.height>"u"||o.height<0?r:o.height,w=d||0,y=p||0;if(c){var S=(v-w)*this.ratio+y,k=(b-w)*this.ratio+y,_=(h-y)/this.ratio+w,I=(m-y)/this.ratio+w,P=Math.max(h,S),E=Math.min(m,k),O=Math.max(v,_),R=Math.min(b,I);n=Bf(n,P,E),r=Bf(r,O,R)}else n=Bf(n,h,m),r=Bf(r,v,b);return{newWidth:n,newHeight:r}},t.prototype.setBoundingClientRect=function(){if(this.props.bounds==="parent"){var n=this.parentNode;if(n){var r=n.getBoundingClientRect();this.parentLeft=r.left,this.parentTop=r.top}}if(this.props.bounds&&typeof this.props.bounds!="string"){var o=this.props.bounds.getBoundingClientRect();this.targetLeft=o.left,this.targetTop=o.top}if(this.resizable){var s=this.resizable.getBoundingClientRect(),a=s.left,c=s.top,d=s.right,p=s.bottom;this.resizableLeft=a,this.resizableRight=d,this.resizableTop=c,this.resizableBottom=p}},t.prototype.onResizeStart=function(n,r){if(!(!this.resizable||!this.window)){var o=0,s=0;if(n.nativeEvent&&wH(n.nativeEvent)?(o=n.nativeEvent.clientX,s=n.nativeEvent.clientY):n.nativeEvent&&Ff(n.nativeEvent)&&(o=n.nativeEvent.touches[0].clientX,s=n.nativeEvent.touches[0].clientY),this.props.onResizeStart&&this.resizable){var a=this.props.onResizeStart(n,r,this.resizable);if(a===!1)return}this.props.size&&(typeof this.props.size.height<"u"&&this.props.size.height!==this.state.height&&this.setState({height:this.props.size.height}),typeof this.props.size.width<"u"&&this.props.size.width!==this.state.width&&this.setState({width:this.props.size.width})),this.ratio=typeof this.props.lockAspectRatio=="number"?this.props.lockAspectRatio:this.size.width/this.size.height;var c,d=this.window.getComputedStyle(this.resizable);if(d.flexBasis!=="auto"){var p=this.parentNode;if(p){var h=this.window.getComputedStyle(p).flexDirection;this.flexDir=h.startsWith("row")?"row":"column",c=d.flexBasis}}this.setBoundingClientRect(),this.bindEvents();var m={original:{x:o,y:s,width:this.size.width,height:this.size.height},isResizing:!0,backgroundStyle:qs(qs({},this.state.backgroundStyle),{cursor:this.window.getComputedStyle(n.target).cursor||"auto"}),direction:r,flexBasis:c};this.setState(m)}},t.prototype.onMouseMove=function(n){var r=this;if(!(!this.state.isResizing||!this.resizable||!this.window)){if(this.window.TouchEvent&&Ff(n))try{n.preventDefault(),n.stopPropagation()}catch{}var o=this.props,s=o.maxWidth,a=o.maxHeight,c=o.minWidth,d=o.minHeight,p=Ff(n)?n.touches[0].clientX:n.clientX,h=Ff(n)?n.touches[0].clientY:n.clientY,m=this.state,v=m.direction,b=m.original,w=m.width,y=m.height,S=this.getParentSize(),k=SH(S,this.window.innerWidth,this.window.innerHeight,s,a,c,d);s=k.maxWidth,a=k.maxHeight,c=k.minWidth,d=k.minHeight;var _=this.calculateNewSizeFromDirection(p,h),I=_.newHeight,P=_.newWidth,E=this.calculateNewMaxFromBoundary(s,a);this.props.snap&&this.props.snap.x&&(P=xS(P,this.props.snap.x,this.props.snapGap)),this.props.snap&&this.props.snap.y&&(I=xS(I,this.props.snap.y,this.props.snapGap));var O=this.calculateNewSizeFromAspectRatio(P,I,{width:E.maxWidth,height:E.maxHeight},{width:c,height:d});if(P=O.newWidth,I=O.newHeight,this.props.grid){var R=yS(P,this.props.grid[0]),M=yS(I,this.props.grid[1]),T=this.props.snapGap||0;P=T===0||Math.abs(R-P)<=T?R:P,I=T===0||Math.abs(M-I)<=T?M:I}var A={width:P-b.width,height:I-b.height};if(w&&typeof w=="string"){if(w.endsWith("%")){var $=P/S.width*100;P=$+"%"}else if(w.endsWith("vw")){var Q=P/this.window.innerWidth*100;P=Q+"vw"}else if(w.endsWith("vh")){var B=P/this.window.innerHeight*100;P=B+"vh"}}if(y&&typeof y=="string"){if(y.endsWith("%")){var $=I/S.height*100;I=$+"%"}else if(y.endsWith("vw")){var Q=I/this.window.innerWidth*100;I=Q+"vw"}else if(y.endsWith("vh")){var B=I/this.window.innerHeight*100;I=B+"vh"}}var V={width:this.createSizeForCssProperty(P,"width"),height:this.createSizeForCssProperty(I,"height")};this.flexDir==="row"?V.flexBasis=V.width:this.flexDir==="column"&&(V.flexBasis=V.height),_i.flushSync(function(){r.setState(V)}),this.props.onResize&&this.props.onResize(n,v,this.resizable,A)}},t.prototype.onMouseUp=function(n){var r=this.state,o=r.isResizing,s=r.direction,a=r.original;if(!(!o||!this.resizable)){var c={width:this.size.width-a.width,height:this.size.height-a.height};this.props.onResizeStop&&this.props.onResizeStop(n,s,this.resizable,c),this.props.size&&this.setState(this.props.size),this.unbindEvents(),this.setState({isResizing:!1,backgroundStyle:qs(qs({},this.state.backgroundStyle),{cursor:"auto"})})}},t.prototype.updateSize=function(n){this.setState({width:n.width,height:n.height})},t.prototype.renderResizer=function(){var n=this,r=this.props,o=r.enable,s=r.handleStyles,a=r.handleClasses,c=r.handleWrapperStyle,d=r.handleWrapperClass,p=r.handleComponent;if(!o)return null;var h=Object.keys(o).map(function(m){return o[m]!==!1?f.createElement(bH,{key:m,direction:m,onResizeStart:n.onResizeStart,replaceStyles:s&&s[m],className:a&&a[m]},p&&p[m]?p[m]:null):null});return f.createElement("div",{className:d,style:c},h)},t.prototype.render=function(){var n=this,r=Object.keys(this.props).reduce(function(a,c){return CH.indexOf(c)!==-1||(a[c]=n.props[c]),a},{}),o=qs(qs(qs({position:"relative",userSelect:this.state.isResizing?"none":"auto"},this.props.style),this.sizeStyle),{maxWidth:this.props.maxWidth,maxHeight:this.props.maxHeight,minWidth:this.props.minWidth,minHeight:this.props.minHeight,boxSizing:"border-box",flexShrink:0});this.state.flexBasis&&(o.flexBasis=this.state.flexBasis);var s=this.props.as||"div";return f.createElement(s,qs({ref:this.ref,style:o,className:this.props.className},r),this.state.isResizing&&f.createElement("div",{style:this.state.backgroundStyle}),this.props.children,this.renderResizer())},t.defaultProps={as:"div",onResizeStart:function(){},onResize:function(){},onResizeStop:function(){},enable:{top:!0,right:!0,bottom:!0,left:!0,topRight:!0,bottomRight:!0,bottomLeft:!0,topLeft:!0},style:{},grid:[1,1],lockAspectRatio:!1,lockAspectRatioExtraWidth:0,lockAspectRatioExtraHeight:0,scale:1,resizeRatio:1,snapGap:0},t}(f.PureComponent);const _H=({direction:e,langDirection:t})=>({top:e==="bottom",right:t!=="rtl"&&e==="left"||t==="rtl"&&e==="right",bottom:e==="top",left:t!=="rtl"&&e==="right"||t==="rtl"&&e==="left"}),PH=({direction:e,minWidth:t,maxWidth:n,minHeight:r,maxHeight:o})=>{const s=t??(["left","right"].includes(e)?10:void 0),a=n??(["left","right"].includes(e)?"95vw":void 0),c=r??(["top","bottom"].includes(e)?10:void 0),d=o??(["top","bottom"].includes(e)?"95vh":void 0);return{...s?{minWidth:s}:{},...a?{maxWidth:a}:{},...c?{minHeight:c}:{},...d?{maxHeight:d}:{}}},va="0.75rem",Wf="1rem",fu="5px",jH=({isResizable:e,direction:t})=>{const n=`calc((2 * ${va} + ${fu}) / -2)`;return t==="top"?{containerStyles:{borderBottomWidth:fu,paddingBottom:Wf},handleStyles:e?{top:{paddingTop:va,paddingBottom:va,bottom:n}}:{}}:t==="left"?{containerStyles:{borderInlineEndWidth:fu,paddingInlineEnd:Wf},handleStyles:e?{right:{paddingInlineStart:va,paddingInlineEnd:va,insetInlineEnd:n}}:{}}:t==="bottom"?{containerStyles:{borderTopWidth:fu,paddingTop:Wf},handleStyles:e?{bottom:{paddingTop:va,paddingBottom:va,top:n}}:{}}:t==="right"?{containerStyles:{borderInlineStartWidth:fu,paddingInlineStart:Wf},handleStyles:e?{left:{paddingInlineStart:va,paddingInlineEnd:va,insetInlineStart:n}}:{}}:{containerStyles:{},handleStyles:{}}},IH=(e,t)=>["top","bottom"].includes(e)?e:e==="left"?t==="rtl"?"right":"left":e==="right"?t==="rtl"?"left":"right":"left",ze=(e,t)=>n=>n==="light"?e:t,EH=Ie(kH,{shouldForwardProp:e=>!["sx"].includes(e)}),i6=({direction:e="left",isResizable:t,isOpen:n,onClose:r,children:o,initialWidth:s,minWidth:a,maxWidth:c,initialHeight:d,minHeight:p,maxHeight:h,onResizeStart:m,onResizeStop:v,onResize:b,sx:w={}})=>{const y=Mc().direction,{colorMode:S}=Ds(),k=f.useRef(null),_=f.useMemo(()=>s??a??(["left","right"].includes(e)?"auto":"100%"),[s,a,e]),I=f.useMemo(()=>d??p??(["top","bottom"].includes(e)?"auto":"100%"),[d,p,e]),[P,E]=f.useState(_),[O,R]=f.useState(I);CN({ref:k,handler:()=>{r()},enabled:n});const M=f.useMemo(()=>t?_H({direction:e,langDirection:y}):{},[t,y,e]),T=f.useMemo(()=>PH({direction:e,minWidth:a,maxWidth:c,minHeight:p,maxHeight:h}),[a,c,p,h,e]),{containerStyles:A,handleStyles:$}=f.useMemo(()=>jH({isResizable:t,direction:e}),[t,e]),Q=f.useMemo(()=>IH(e,y),[e,y]);return f.useEffect(()=>{["left","right"].includes(e)&&R("100vh"),["top","bottom"].includes(e)&&E("100vw")},[e]),i.jsx(A3,{direction:Q,in:n,motionProps:{initial:!1},style:{width:"full"},children:i.jsx(Oe,{ref:k,sx:{width:"full",height:"full"},children:i.jsx(EH,{size:{width:t?P:_,height:t?O:I},enable:M,handleStyles:$,...T,sx:{borderColor:ze("base.200","base.800")(S),p:4,bg:ze("base.50","base.900")(S),height:"full",shadow:n?"dark-lg":void 0,...A,...w},onResizeStart:(B,V,q)=>{m&&m(B,V,q)},onResize:(B,V,q,G)=>{b&&b(B,V,q,G)},onResizeStop:(B,V,q,G)=>{["left","right"].includes(V)&&E(Number(P)+G.width),["top","bottom"].includes(V)&&R(Number(O)+G.height),v&&v(B,V,q,G)},children:o})})})},OH=Te((e,t)=>{const{children:n,tooltip:r="",tooltipProps:{placement:o="top",hasArrow:s=!0,...a}={},isChecked:c,...d}=e;return i.jsx(wn,{label:r,placement:o,hasArrow:s,...a,children:i.jsx(gc,{ref:t,colorScheme:c?"accent":"base",...d,children:n})})}),rn=f.memo(OH);var l6={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},SS=F.createContext&&F.createContext(l6),fi=globalThis&&globalThis.__assign||function(){return fi=Object.assign||function(e){for(var t,n=1,r=arguments.length;nt(e[n],n,e));return e}function ro(e,t){const n=Ii(t);if(Rs(t)||n){let o=n?"":{};if(e){const s=window.getComputedStyle(e,null);o=n?jS(e,s,t):t.reduce((a,c)=>(a[c]=jS(e,s,c),a),o)}return o}e&&_n(Bo(t),o=>MW(e,o,t[o]))}const xs=(e,t)=>{const{o:n,u:r,_:o}=e;let s=n,a;const c=(h,m)=>{const v=s,b=h,w=m||(r?!r(v,b):v!==b);return(w||o)&&(s=b,a=v),[s,w,a]};return[t?h=>c(t(s,a),h):c,h=>[s,!!h,a]]},Dd=()=>typeof window<"u",C6=Dd()&&Node.ELEMENT_NODE,{toString:vW,hasOwnProperty:D0}=Object.prototype,Ha=e=>e===void 0,Pm=e=>e===null,bW=e=>Ha(e)||Pm(e)?`${e}`:vW.call(e).replace(/^\[object (.+)\]$/,"$1").toLowerCase(),pi=e=>typeof e=="number",Ii=e=>typeof e=="string",Vb=e=>typeof e=="boolean",Os=e=>typeof e=="function",Rs=e=>Array.isArray(e),ed=e=>typeof e=="object"&&!Rs(e)&&!Pm(e),jm=e=>{const t=!!e&&e.length,n=pi(t)&&t>-1&&t%1==0;return Rs(e)||!Os(e)&&n?t>0&&ed(e)?t-1 in e:!0:!1},Xv=e=>{if(!e||!ed(e)||bW(e)!=="object")return!1;let t;const n="constructor",r=e[n],o=r&&r.prototype,s=D0.call(e,n),a=o&&D0.call(o,"isPrototypeOf");if(r&&!s&&!a)return!1;for(t in e);return Ha(t)||D0.call(e,t)},Xp=e=>{const t=HTMLElement;return e?t?e instanceof t:e.nodeType===C6:!1},Im=e=>{const t=Element;return e?t?e instanceof t:e.nodeType===C6:!1},Ub=(e,t,n)=>e.indexOf(t,n),Mn=(e,t,n)=>(!n&&!Ii(t)&&jm(t)?Array.prototype.push.apply(e,t):e.push(t),e),il=e=>{const t=Array.from,n=[];return t&&e?t(e):(e instanceof Set?e.forEach(r=>{Mn(n,r)}):_n(e,r=>{Mn(n,r)}),n)},Gb=e=>!!e&&e.length===0,la=(e,t,n)=>{_n(e,o=>o&&o.apply(void 0,t||[])),!n&&(e.length=0)},Em=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Bo=e=>e?Object.keys(e):[],pr=(e,t,n,r,o,s,a)=>{const c=[t,n,r,o,s,a];return(typeof e!="object"||Pm(e))&&!Os(e)&&(e={}),_n(c,d=>{_n(Bo(d),p=>{const h=d[p];if(e===h)return!0;const m=Rs(h);if(h&&(Xv(h)||m)){const v=e[p];let b=v;m&&!Rs(v)?b=[]:!m&&!Xv(v)&&(b={}),e[p]=pr(b,h)}else e[p]=h})}),e},qb=e=>{for(const t in e)return!1;return!0},k6=(e,t,n,r)=>{if(Ha(r))return n?n[e]:t;n&&(Ii(r)||pi(r))&&(n[e]=r)},no=(e,t,n)=>{if(Ha(n))return e?e.getAttribute(t):null;e&&e.setAttribute(t,n)},xo=(e,t)=>{e&&e.removeAttribute(t)},Qi=(e,t,n,r)=>{if(n){const o=no(e,t)||"",s=new Set(o.split(" "));s[r?"add":"delete"](n);const a=il(s).join(" ").trim();no(e,t,a)}},yW=(e,t,n)=>{const r=no(e,t)||"";return new Set(r.split(" ")).has(n)},_s=(e,t)=>k6("scrollLeft",0,e,t),Ca=(e,t)=>k6("scrollTop",0,e,t),Qv=Dd()&&Element.prototype,_6=(e,t)=>{const n=[],r=t?Im(t)?t:null:document;return r?Mn(n,r.querySelectorAll(e)):n},xW=(e,t)=>{const n=t?Im(t)?t:null:document;return n?n.querySelector(e):null},Qp=(e,t)=>Im(e)?(Qv.matches||Qv.msMatchesSelector).call(e,t):!1,Kb=e=>e?il(e.childNodes):[],Ta=e=>e?e.parentElement:null,Yl=(e,t)=>{if(Im(e)){const n=Qv.closest;if(n)return n.call(e,t);do{if(Qp(e,t))return e;e=Ta(e)}while(e)}return null},wW=(e,t,n)=>{const r=e&&Yl(e,t),o=e&&xW(n,r),s=Yl(o,t)===r;return r&&o?r===e||o===e||s&&Yl(Yl(e,n),t)!==r:!1},Yb=(e,t,n)=>{if(n&&e){let r=t,o;jm(n)?(o=document.createDocumentFragment(),_n(n,s=>{s===r&&(r=s.previousSibling),o.appendChild(s)})):o=n,t&&(r?r!==t&&(r=r.nextSibling):r=e.firstChild),e.insertBefore(o,r||null)}},ts=(e,t)=>{Yb(e,null,t)},SW=(e,t)=>{Yb(Ta(e),e,t)},kS=(e,t)=>{Yb(Ta(e),e&&e.nextSibling,t)},oa=e=>{if(jm(e))_n(il(e),t=>oa(t));else if(e){const t=Ta(e);t&&t.removeChild(e)}},Ji=e=>{const t=document.createElement("div");return e&&no(t,"class",e),t},P6=e=>{const t=Ji();return t.innerHTML=e.trim(),_n(Kb(t),n=>oa(n))},Jv=e=>e.charAt(0).toUpperCase()+e.slice(1),CW=()=>Ji().style,kW=["-webkit-","-moz-","-o-","-ms-"],_W=["WebKit","Moz","O","MS","webkit","moz","o","ms"],T0={},A0={},PW=e=>{let t=A0[e];if(Em(A0,e))return t;const n=Jv(e),r=CW();return _n(kW,o=>{const s=o.replace(/-/g,"");return!(t=[e,o+e,s+n,Jv(s)+n].find(c=>r[c]!==void 0))}),A0[e]=t||""},Td=e=>{if(Dd()){let t=T0[e]||window[e];return Em(T0,e)||(_n(_W,n=>(t=t||window[n+Jv(e)],!t)),T0[e]=t),t}},jW=Td("MutationObserver"),_S=Td("IntersectionObserver"),Xl=Td("ResizeObserver"),j6=Td("cancelAnimationFrame"),I6=Td("requestAnimationFrame"),Jp=Dd()&&window.setTimeout,Zv=Dd()&&window.clearTimeout,IW=/[^\x20\t\r\n\f]+/g,E6=(e,t,n)=>{const r=e&&e.classList;let o,s=0,a=!1;if(r&&t&&Ii(t)){const c=t.match(IW)||[];for(a=c.length>0;o=c[s++];)a=!!n(r,o)&&a}return a},Xb=(e,t)=>{E6(e,t,(n,r)=>n.remove(r))},ka=(e,t)=>(E6(e,t,(n,r)=>n.add(r)),Xb.bind(0,e,t)),Om=(e,t,n,r)=>{if(e&&t){let o=!0;return _n(n,s=>{const a=r?r(e[s]):e[s],c=r?r(t[s]):t[s];a!==c&&(o=!1)}),o}return!1},O6=(e,t)=>Om(e,t,["w","h"]),R6=(e,t)=>Om(e,t,["x","y"]),EW=(e,t)=>Om(e,t,["t","r","b","l"]),PS=(e,t,n)=>Om(e,t,["width","height"],n&&(r=>Math.round(r))),es=()=>{},Ul=e=>{let t;const n=e?Jp:I6,r=e?Zv:j6;return[o=>{r(t),t=n(o,Os(e)?e():e)},()=>r(t)]},Qb=(e,t)=>{let n,r,o,s=es;const{v:a,g:c,p:d}=t||{},p=function(w){s(),Zv(n),n=r=void 0,s=es,e.apply(this,w)},h=b=>d&&r?d(r,b):b,m=()=>{s!==es&&p(h(o)||o)},v=function(){const w=il(arguments),y=Os(a)?a():a;if(pi(y)&&y>=0){const k=Os(c)?c():c,_=pi(k)&&k>=0,I=y>0?Jp:I6,P=y>0?Zv:j6,O=h(w)||w,R=p.bind(0,O);s();const M=I(R,y);s=()=>P(M),_&&!n&&(n=Jp(m,k)),r=o=O}else p(w)};return v.m=m,v},OW={opacity:1,zindex:1},Vf=(e,t)=>{const n=t?parseFloat(e):parseInt(e,10);return n===n?n:0},RW=(e,t)=>!OW[e.toLowerCase()]&&pi(t)?`${t}px`:t,jS=(e,t,n)=>t!=null?t[n]||t.getPropertyValue(n):e.style[n],MW=(e,t,n)=>{try{const{style:r}=e;Ha(r[t])?r.setProperty(t,n):r[t]=RW(t,n)}catch{}},td=e=>ro(e,"direction")==="rtl",IS=(e,t,n)=>{const r=t?`${t}-`:"",o=n?`-${n}`:"",s=`${r}top${o}`,a=`${r}right${o}`,c=`${r}bottom${o}`,d=`${r}left${o}`,p=ro(e,[s,a,c,d]);return{t:Vf(p[s],!0),r:Vf(p[a],!0),b:Vf(p[c],!0),l:Vf(p[d],!0)}},{round:ES}=Math,Jb={w:0,h:0},nd=e=>e?{w:e.offsetWidth,h:e.offsetHeight}:Jb,Pp=e=>e?{w:e.clientWidth,h:e.clientHeight}:Jb,Zp=e=>e?{w:e.scrollWidth,h:e.scrollHeight}:Jb,eh=e=>{const t=parseFloat(ro(e,"height"))||0,n=parseFloat(ro(e,"width"))||0;return{w:n-ES(n),h:t-ES(t)}},Zs=e=>e.getBoundingClientRect();let Uf;const DW=()=>{if(Ha(Uf)){Uf=!1;try{window.addEventListener("test",null,Object.defineProperty({},"passive",{get(){Uf=!0}}))}catch{}}return Uf},M6=e=>e.split(" "),TW=(e,t,n,r)=>{_n(M6(t),o=>{e.removeEventListener(o,n,r)})},Dr=(e,t,n,r)=>{var o;const s=DW(),a=(o=s&&r&&r.S)!=null?o:s,c=r&&r.$||!1,d=r&&r.C||!1,p=[],h=s?{passive:a,capture:c}:c;return _n(M6(t),m=>{const v=d?b=>{e.removeEventListener(m,v,c),n&&n(b)}:n;Mn(p,TW.bind(null,e,m,v,c)),e.addEventListener(m,v,h)}),la.bind(0,p)},D6=e=>e.stopPropagation(),T6=e=>e.preventDefault(),AW={x:0,y:0},N0=e=>{const t=e?Zs(e):0;return t?{x:t.left+window.pageYOffset,y:t.top+window.pageXOffset}:AW},OS=(e,t)=>{_n(Rs(t)?t:[t],e)},Zb=e=>{const t=new Map,n=(s,a)=>{if(s){const c=t.get(s);OS(d=>{c&&c[d?"delete":"clear"](d)},a)}else t.forEach(c=>{c.clear()}),t.clear()},r=(s,a)=>{if(Ii(s)){const p=t.get(s)||new Set;return t.set(s,p),OS(h=>{Os(h)&&p.add(h)},a),n.bind(0,s,a)}Vb(a)&&a&&n();const c=Bo(s),d=[];return _n(c,p=>{const h=s[p];h&&Mn(d,r(p,h))}),la.bind(0,d)},o=(s,a)=>{const c=t.get(s);_n(il(c),d=>{a&&!Gb(a)?d.apply(0,a):d()})};return r(e||{}),[r,n,o]},RS=e=>JSON.stringify(e,(t,n)=>{if(Os(n))throw new Error;return n}),NW={paddingAbsolute:!1,showNativeOverlaidScrollbars:!1,update:{elementEvents:[["img","load"]],debounce:[0,33],attributes:null,ignoreMutation:null},overflow:{x:"scroll",y:"scroll"},scrollbars:{theme:"os-theme-dark",visibility:"auto",autoHide:"never",autoHideDelay:1300,dragScroll:!0,clickScroll:!1,pointers:["mouse","touch","pen"]}},A6=(e,t)=>{const n={},r=Bo(t).concat(Bo(e));return _n(r,o=>{const s=e[o],a=t[o];if(ed(s)&&ed(a))pr(n[o]={},A6(s,a)),qb(n[o])&&delete n[o];else if(Em(t,o)&&a!==s){let c=!0;if(Rs(s)||Rs(a))try{RS(s)===RS(a)&&(c=!1)}catch{}c&&(n[o]=a)}}),n},N6="os-environment",$6=`${N6}-flexbox-glue`,$W=`${$6}-max`,z6="os-scrollbar-hidden",$0="data-overlayscrollbars-initialize",ws="data-overlayscrollbars",L6=`${ws}-overflow-x`,B6=`${ws}-overflow-y`,cc="overflowVisible",zW="scrollbarHidden",MS="scrollbarPressed",th="updating",oi="data-overlayscrollbars-viewport",z0="arrange",F6="scrollbarHidden",uc=cc,e1="data-overlayscrollbars-padding",LW=uc,DS="data-overlayscrollbars-content",ey="os-size-observer",BW=`${ey}-appear`,FW=`${ey}-listener`,HW="os-trinsic-observer",WW="os-no-css-vars",VW="os-theme-none",Io="os-scrollbar",UW=`${Io}-rtl`,GW=`${Io}-horizontal`,qW=`${Io}-vertical`,H6=`${Io}-track`,ty=`${Io}-handle`,KW=`${Io}-visible`,YW=`${Io}-cornerless`,TS=`${Io}-transitionless`,AS=`${Io}-interaction`,NS=`${Io}-unusable`,$S=`${Io}-auto-hidden`,zS=`${Io}-wheel`,XW=`${H6}-interactive`,QW=`${ty}-interactive`,W6={},ll=()=>W6,JW=e=>{const t=[];return _n(Rs(e)?e:[e],n=>{const r=Bo(n);_n(r,o=>{Mn(t,W6[o]=n[o])})}),t},ZW="__osOptionsValidationPlugin",eV="__osSizeObserverPlugin",ny="__osScrollbarsHidingPlugin",tV="__osClickScrollPlugin";let L0;const LS=(e,t,n,r)=>{ts(e,t);const o=Pp(t),s=nd(t),a=eh(n);return r&&oa(t),{x:s.h-o.h+a.h,y:s.w-o.w+a.w}},nV=e=>{let t=!1;const n=ka(e,z6);try{t=ro(e,PW("scrollbar-width"))==="none"||window.getComputedStyle(e,"::-webkit-scrollbar").getPropertyValue("display")==="none"}catch{}return n(),t},rV=(e,t)=>{const n="hidden";ro(e,{overflowX:n,overflowY:n,direction:"rtl"}),_s(e,0);const r=N0(e),o=N0(t);_s(e,-999);const s=N0(t);return{i:r.x===o.x,n:o.x!==s.x}},oV=(e,t)=>{const n=ka(e,$6),r=Zs(e),o=Zs(t),s=PS(o,r,!0),a=ka(e,$W),c=Zs(e),d=Zs(t),p=PS(d,c,!0);return n(),a(),s&&p},sV=()=>{const{body:e}=document,n=P6(`
`)[0],r=n.firstChild,[o,,s]=Zb(),[a,c]=xs({o:LS(e,n,r),u:R6},LS.bind(0,e,n,r,!0)),[d]=c(),p=nV(n),h={x:d.x===0,y:d.y===0},m={elements:{host:null,padding:!p,viewport:_=>p&&_===_.ownerDocument.body&&_,content:!1},scrollbars:{slot:!0},cancel:{nativeScrollbarsOverlaid:!1,body:null}},v=pr({},NW),b=pr.bind(0,{},v),w=pr.bind(0,{},m),y={k:d,A:h,I:p,L:ro(n,"zIndex")==="-1",B:rV(n,r),V:oV(n,r),Y:o.bind(0,"z"),j:o.bind(0,"r"),N:w,q:_=>pr(m,_)&&w(),F:b,G:_=>pr(v,_)&&b(),X:pr({},m),U:pr({},v)},S=window.addEventListener,k=Qb(_=>s(_?"z":"r"),{v:33,g:99});if(xo(n,"style"),oa(n),S("resize",k.bind(0,!1)),!p&&(!h.x||!h.y)){let _;S("resize",()=>{const I=ll()[ny];_=_||I&&I.R(),_&&_(y,a,k.bind(0,!0))})}return y},Eo=()=>(L0||(L0=sV()),L0),ry=(e,t)=>Os(t)?t.apply(0,e):t,aV=(e,t,n,r)=>{const o=Ha(r)?n:r;return ry(e,o)||t.apply(0,e)},V6=(e,t,n,r)=>{const o=Ha(r)?n:r,s=ry(e,o);return!!s&&(Xp(s)?s:t.apply(0,e))},iV=(e,t,n)=>{const{nativeScrollbarsOverlaid:r,body:o}=n||{},{A:s,I:a}=Eo(),{nativeScrollbarsOverlaid:c,body:d}=t,p=r??c,h=Ha(o)?d:o,m=(s.x||s.y)&&p,v=e&&(Pm(h)?!a:h);return!!m||!!v},oy=new WeakMap,lV=(e,t)=>{oy.set(e,t)},cV=e=>{oy.delete(e)},U6=e=>oy.get(e),BS=(e,t)=>e?t.split(".").reduce((n,r)=>n&&Em(n,r)?n[r]:void 0,e):void 0,t1=(e,t,n)=>r=>[BS(e,r),n||BS(t,r)!==void 0],G6=e=>{let t=e;return[()=>t,n=>{t=pr({},t,n)}]},Gf="tabindex",qf=Ji.bind(0,""),B0=e=>{ts(Ta(e),Kb(e)),oa(e)},uV=e=>{const t=Eo(),{N:n,I:r}=t,o=ll()[ny],s=o&&o.T,{elements:a}=n(),{host:c,padding:d,viewport:p,content:h}=a,m=Xp(e),v=m?{}:e,{elements:b}=v,{host:w,padding:y,viewport:S,content:k}=b||{},_=m?e:v.target,I=Qp(_,"textarea"),P=_.ownerDocument,E=P.documentElement,O=_===P.body,R=P.defaultView,M=aV.bind(0,[_]),T=V6.bind(0,[_]),A=ry.bind(0,[_]),$=M.bind(0,qf,p),Q=T.bind(0,qf,h),B=$(S),V=B===_,q=V&&O,G=!V&&Q(k),D=!V&&Xp(B)&&B===G,L=D&&!!A(h),W=L?$():B,Y=L?G:Q(),ye=q?E:D?W:B,ue=I?M(qf,c,w):_,X=q?ye:ue,K=D?Y:G,U=P.activeElement,se=!V&&R.top===R&&U===_,re={W:_,Z:X,J:ye,K:!V&&T(qf,d,y),tt:K,nt:!V&&!r&&s&&s(t),ot:q?E:ye,st:q?P:ye,et:R,ct:P,rt:I,it:O,lt:m,ut:V,dt:D,ft:(vt,bt)=>yW(ye,V?ws:oi,V?bt:vt),_t:(vt,bt,we)=>Qi(ye,V?ws:oi,V?bt:vt,we)},oe=Bo(re).reduce((vt,bt)=>{const we=re[bt];return Mn(vt,we&&!Ta(we)?we:!1)},[]),pe=vt=>vt?Ub(oe,vt)>-1:null,{W:le,Z:ge,K:_e,J:ie,tt:Se,nt:Fe}=re,Ae=[()=>{xo(ge,ws),xo(ge,$0),xo(le,$0),O&&(xo(E,ws),xo(E,$0))}],He=I&&pe(ge);let Ct=I?le:Kb([Se,ie,_e,ge,le].find(vt=>pe(vt)===!1));const ct=q?le:Se||ie;return[re,()=>{no(ge,ws,V?"viewport":"host"),no(_e,e1,""),no(Se,DS,""),V||no(ie,oi,"");const vt=O&&!V?ka(Ta(_),z6):es;if(He&&(kS(le,ge),Mn(Ae,()=>{kS(ge,le),oa(ge)})),ts(ct,Ct),ts(ge,_e),ts(_e||ge,!V&&ie),ts(ie,Se),Mn(Ae,()=>{vt(),xo(_e,e1),xo(Se,DS),xo(ie,L6),xo(ie,B6),xo(ie,oi),pe(Se)&&B0(Se),pe(ie)&&B0(ie),pe(_e)&&B0(_e)}),r&&!V&&(Qi(ie,oi,F6,!0),Mn(Ae,xo.bind(0,ie,oi))),Fe&&(SW(ie,Fe),Mn(Ae,oa.bind(0,Fe))),se){const bt=no(ie,Gf);no(ie,Gf,"-1"),ie.focus();const we=()=>bt?no(ie,Gf,bt):xo(ie,Gf),Re=Dr(P,"pointerdown keydown",()=>{we(),Re()});Mn(Ae,[we,Re])}else U&&U.focus&&U.focus();Ct=0},la.bind(0,Ae)]},dV=(e,t)=>{const{tt:n}=e,[r]=t;return o=>{const{V:s}=Eo(),{ht:a}=r(),{vt:c}=o,d=(n||!s)&&c;return d&&ro(n,{height:a?"":"100%"}),{gt:d,wt:d}}},fV=(e,t)=>{const[n,r]=t,{Z:o,K:s,J:a,ut:c}=e,[d,p]=xs({u:EW,o:IS()},IS.bind(0,o,"padding",""));return(h,m,v)=>{let[b,w]=p(v);const{I:y,V:S}=Eo(),{bt:k}=n(),{gt:_,wt:I,yt:P}=h,[E,O]=m("paddingAbsolute");(_||w||!S&&I)&&([b,w]=d(v));const M=!c&&(O||P||w);if(M){const T=!E||!s&&!y,A=b.r+b.l,$=b.t+b.b,Q={marginRight:T&&!k?-A:0,marginBottom:T?-$:0,marginLeft:T&&k?-A:0,top:T?-b.t:0,right:T?k?-b.r:"auto":0,left:T?k?"auto":-b.l:0,width:T?`calc(100% + ${A}px)`:""},B={paddingTop:T?b.t:0,paddingRight:T?b.r:0,paddingBottom:T?b.b:0,paddingLeft:T?b.l:0};ro(s||a,Q),ro(a,B),r({K:b,St:!T,P:s?B:pr({},Q,B)})}return{xt:M}}},{max:n1}=Math,si=n1.bind(0,0),q6="visible",FS="hidden",pV=42,Kf={u:O6,o:{w:0,h:0}},hV={u:R6,o:{x:FS,y:FS}},mV=(e,t)=>{const n=window.devicePixelRatio%1!==0?1:0,r={w:si(e.w-t.w),h:si(e.h-t.h)};return{w:r.w>n?r.w:0,h:r.h>n?r.h:0}},Yf=e=>e.indexOf(q6)===0,gV=(e,t)=>{const[n,r]=t,{Z:o,K:s,J:a,nt:c,ut:d,_t:p,it:h,et:m}=e,{k:v,V:b,I:w,A:y}=Eo(),S=ll()[ny],k=!d&&!w&&(y.x||y.y),_=h&&d,[I,P]=xs(Kf,eh.bind(0,a)),[E,O]=xs(Kf,Zp.bind(0,a)),[R,M]=xs(Kf),[T,A]=xs(Kf),[$]=xs(hV),Q=(L,W)=>{if(ro(a,{height:""}),W){const{St:Y,K:ae}=n(),{$t:ye,D:ue}=L,X=eh(o),K=Pp(o),U=ro(a,"boxSizing")==="content-box",se=Y||U?ae.b+ae.t:0,re=!(y.x&&U);ro(a,{height:K.h+X.h+(ye.x&&re?ue.x:0)-se})}},B=(L,W)=>{const Y=!w&&!L?pV:0,ae=(pe,le,ge)=>{const _e=ro(a,pe),Se=(W?W[pe]:_e)==="scroll";return[_e,Se,Se&&!w?le?Y:ge:0,le&&!!Y]},[ye,ue,X,K]=ae("overflowX",y.x,v.x),[U,se,re,oe]=ae("overflowY",y.y,v.y);return{Ct:{x:ye,y:U},$t:{x:ue,y:se},D:{x:X,y:re},M:{x:K,y:oe}}},V=(L,W,Y,ae)=>{const ye=(se,re)=>{const oe=Yf(se),pe=re&&oe&&se.replace(`${q6}-`,"")||"";return[re&&!oe?se:"",Yf(pe)?"hidden":pe]},[ue,X]=ye(Y.x,W.x),[K,U]=ye(Y.y,W.y);return ae.overflowX=X&&K?X:ue,ae.overflowY=U&&ue?U:K,B(L,ae)},q=(L,W,Y,ae)=>{const{D:ye,M:ue}=L,{x:X,y:K}=ue,{x:U,y:se}=ye,{P:re}=n(),oe=W?"marginLeft":"marginRight",pe=W?"paddingLeft":"paddingRight",le=re[oe],ge=re.marginBottom,_e=re[pe],ie=re.paddingBottom;ae.width=`calc(100% + ${se+-1*le}px)`,ae[oe]=-se+le,ae.marginBottom=-U+ge,Y&&(ae[pe]=_e+(K?se:0),ae.paddingBottom=ie+(X?U:0))},[G,D]=S?S.H(k,b,a,c,n,B,q):[()=>k,()=>[es]];return(L,W,Y)=>{const{gt:ae,Ot:ye,wt:ue,xt:X,vt:K,yt:U}=L,{ht:se,bt:re}=n(),[oe,pe]=W("showNativeOverlaidScrollbars"),[le,ge]=W("overflow"),_e=oe&&y.x&&y.y,ie=!d&&!b&&(ae||ue||ye||pe||K),Se=Yf(le.x),Fe=Yf(le.y),Ae=Se||Fe;let He=P(Y),Ct=O(Y),ct=M(Y),on=A(Y),vt;if(pe&&w&&p(F6,zW,!_e),ie&&(vt=B(_e),Q(vt,se)),ae||X||ue||U||pe){Ae&&p(uc,cc,!1);const[Pe,Je]=D(_e,re,vt),[Xe,dt]=He=I(Y),[Lt,lr]=Ct=E(Y),pn=Pp(a);let ln=Lt,Fr=pn;Pe(),(lr||dt||pe)&&Je&&!_e&&G(Je,Lt,Xe,re)&&(Fr=Pp(a),ln=Zp(a));const br={w:si(n1(Lt.w,ln.w)+Xe.w),h:si(n1(Lt.h,ln.h)+Xe.h)},Fn={w:si((_?m.innerWidth:Fr.w+si(pn.w-Lt.w))+Xe.w),h:si((_?m.innerHeight+Xe.h:Fr.h+si(pn.h-Lt.h))+Xe.h)};on=T(Fn),ct=R(mV(br,Fn),Y)}const[bt,we]=on,[Re,Pt]=ct,[At,xe]=Ct,[ht,$t]=He,zt={x:Re.w>0,y:Re.h>0},Ne=Se&&Fe&&(zt.x||zt.y)||Se&&zt.x&&!zt.y||Fe&&zt.y&&!zt.x;if(X||U||$t||xe||we||Pt||ge||pe||ie){const Pe={marginRight:0,marginBottom:0,marginLeft:0,width:"",overflowY:"",overflowX:""},Je=V(_e,zt,le,Pe),Xe=G(Je,At,ht,re);d||q(Je,re,Xe,Pe),ie&&Q(Je,se),d?(no(o,L6,Pe.overflowX),no(o,B6,Pe.overflowY)):ro(a,Pe)}Qi(o,ws,cc,Ne),Qi(s,e1,LW,Ne),d||Qi(a,oi,uc,Ae);const[qe,Pn]=$(B(_e).Ct);return r({Ct:qe,zt:{x:bt.w,y:bt.h},Tt:{x:Re.w,y:Re.h},Et:zt}),{It:Pn,At:we,Lt:Pt}}},HS=(e,t,n)=>{const r={},o=t||{},s=Bo(e).concat(Bo(o));return _n(s,a=>{const c=e[a],d=o[a];r[a]=!!(n||c||d)}),r},vV=(e,t)=>{const{W:n,J:r,_t:o,ut:s}=e,{I:a,A:c,V:d}=Eo(),p=!a&&(c.x||c.y),h=[dV(e,t),fV(e,t),gV(e,t)];return(m,v,b)=>{const w=HS(pr({gt:!1,xt:!1,yt:!1,vt:!1,At:!1,Lt:!1,It:!1,Ot:!1,wt:!1},v),{},b),y=p||!d,S=y&&_s(r),k=y&&Ca(r);o("",th,!0);let _=w;return _n(h,I=>{_=HS(_,I(_,m,!!b)||{},b)}),_s(r,S),Ca(r,k),o("",th),s||(_s(n,0),Ca(n,0)),_}},bV=(e,t,n)=>{let r,o=!1;const s=()=>{o=!0},a=c=>{if(n){const d=n.reduce((p,h)=>{if(h){const[m,v]=h,b=v&&m&&(c?c(m):_6(m,e));b&&b.length&&v&&Ii(v)&&Mn(p,[b,v.trim()],!0)}return p},[]);_n(d,p=>_n(p[0],h=>{const m=p[1],v=r.get(h)||[];if(e.contains(h)){const w=Dr(h,m,y=>{o?(w(),r.delete(h)):t(y)});r.set(h,Mn(v,w))}else la(v),r.delete(h)}))}};return n&&(r=new WeakMap,a()),[s,a]},WS=(e,t,n,r)=>{let o=!1;const{Ht:s,Pt:a,Dt:c,Mt:d,Rt:p,kt:h}=r||{},m=Qb(()=>{o&&n(!0)},{v:33,g:99}),[v,b]=bV(e,m,c),w=s||[],y=a||[],S=w.concat(y),k=(I,P)=>{const E=p||es,O=h||es,R=new Set,M=new Set;let T=!1,A=!1;if(_n(I,$=>{const{attributeName:Q,target:B,type:V,oldValue:q,addedNodes:G,removedNodes:D}=$,L=V==="attributes",W=V==="childList",Y=e===B,ae=L&&Ii(Q)?no(B,Q):0,ye=ae!==0&&q!==ae,ue=Ub(y,Q)>-1&&ye;if(t&&(W||!Y)){const X=!L,K=L&&ye,U=K&&d&&Qp(B,d),re=(U?!E(B,Q,q,ae):X||K)&&!O($,!!U,e,r);_n(G,oe=>R.add(oe)),_n(D,oe=>R.add(oe)),A=A||re}!t&&Y&&ye&&!E(B,Q,q,ae)&&(M.add(Q),T=T||ue)}),R.size>0&&b($=>il(R).reduce((Q,B)=>(Mn(Q,_6($,B)),Qp(B,$)?Mn(Q,B):Q),[])),t)return!P&&A&&n(!1),[!1];if(M.size>0||T){const $=[il(M),T];return!P&&n.apply(0,$),$}},_=new jW(I=>k(I));return _.observe(e,{attributes:!0,attributeOldValue:!0,attributeFilter:S,subtree:t,childList:t,characterData:t}),o=!0,[()=>{o&&(v(),_.disconnect(),o=!1)},()=>{if(o){m.m();const I=_.takeRecords();return!Gb(I)&&k(I,!0)}}]},Xf=3333333,Qf=e=>e&&(e.height||e.width),K6=(e,t,n)=>{const{Bt:r=!1,Vt:o=!1}=n||{},s=ll()[eV],{B:a}=Eo(),d=P6(`
`)[0],p=d.firstChild,h=td.bind(0,e),[m]=xs({o:void 0,_:!0,u:(y,S)=>!(!y||!Qf(y)&&Qf(S))}),v=y=>{const S=Rs(y)&&y.length>0&&ed(y[0]),k=!S&&Vb(y[0]);let _=!1,I=!1,P=!0;if(S){const[E,,O]=m(y.pop().contentRect),R=Qf(E),M=Qf(O);_=!O||!R,I=!M&&R,P=!_}else k?[,P]=y:I=y===!0;if(r&&P){const E=k?y[0]:td(d);_s(d,E?a.n?-Xf:a.i?0:Xf:Xf),Ca(d,Xf)}_||t({gt:!k,Yt:k?y:void 0,Vt:!!I})},b=[];let w=o?v:!1;return[()=>{la(b),oa(d)},()=>{if(Xl){const y=new Xl(v);y.observe(p),Mn(b,()=>{y.disconnect()})}else if(s){const[y,S]=s.O(p,v,o);w=y,Mn(b,S)}if(r){const[y]=xs({o:void 0},h);Mn(b,Dr(d,"scroll",S=>{const k=y(),[_,I,P]=k;I&&(Xb(p,"ltr rtl"),_?ka(p,"rtl"):ka(p,"ltr"),v([!!_,I,P])),D6(S)}))}w&&(ka(d,BW),Mn(b,Dr(d,"animationstart",w,{C:!!Xl}))),(Xl||s)&&ts(e,d)}]},yV=e=>e.h===0||e.isIntersecting||e.intersectionRatio>0,xV=(e,t)=>{let n;const r=Ji(HW),o=[],[s]=xs({o:!1}),a=(d,p)=>{if(d){const h=s(yV(d)),[,m]=h;if(m)return!p&&t(h),[h]}},c=(d,p)=>{if(d&&d.length>0)return a(d.pop(),p)};return[()=>{la(o),oa(r)},()=>{if(_S)n=new _S(d=>c(d),{root:e}),n.observe(r),Mn(o,()=>{n.disconnect()});else{const d=()=>{const m=nd(r);a(m)},[p,h]=K6(r,d);Mn(o,p),h(),d()}ts(e,r)},()=>{if(n)return c(n.takeRecords(),!0)}]},VS=`[${ws}]`,wV=`[${oi}]`,F0=["tabindex"],US=["wrap","cols","rows"],H0=["id","class","style","open"],SV=(e,t,n)=>{let r,o,s;const{Z:a,J:c,tt:d,rt:p,ut:h,ft:m,_t:v}=e,{V:b}=Eo(),[w]=xs({u:O6,o:{w:0,h:0}},()=>{const V=m(uc,cc),q=m(z0,""),G=q&&_s(c),D=q&&Ca(c);v(uc,cc),v(z0,""),v("",th,!0);const L=Zp(d),W=Zp(c),Y=eh(c);return v(uc,cc,V),v(z0,"",q),v("",th),_s(c,G),Ca(c,D),{w:W.w+L.w+Y.w,h:W.h+L.h+Y.h}}),y=p?US:H0.concat(US),S=Qb(n,{v:()=>r,g:()=>o,p(V,q){const[G]=V,[D]=q;return[Bo(G).concat(Bo(D)).reduce((L,W)=>(L[W]=G[W]||D[W],L),{})]}}),k=V=>{_n(V||F0,q=>{if(Ub(F0,q)>-1){const G=no(a,q);Ii(G)?no(c,q,G):xo(c,q)}})},_=(V,q)=>{const[G,D]=V,L={vt:D};return t({ht:G}),!q&&n(L),L},I=({gt:V,Yt:q,Vt:G})=>{const D=!V||G?n:S;let L=!1;if(q){const[W,Y]=q;L=Y,t({bt:W})}D({gt:V,yt:L})},P=(V,q)=>{const[,G]=w(),D={wt:G};return G&&!q&&(V?n:S)(D),D},E=(V,q,G)=>{const D={Ot:q};return q?!G&&S(D):h||k(V),D},[O,R,M]=d||!b?xV(a,_):[es,es,es],[T,A]=h?[es,es]:K6(a,I,{Vt:!0,Bt:!0}),[$,Q]=WS(a,!1,E,{Pt:H0,Ht:H0.concat(F0)}),B=h&&Xl&&new Xl(I.bind(0,{gt:!0}));return B&&B.observe(a),k(),[()=>{O(),T(),s&&s[0](),B&&B.disconnect(),$()},()=>{A(),R()},()=>{const V={},q=Q(),G=M(),D=s&&s[1]();return q&&pr(V,E.apply(0,Mn(q,!0))),G&&pr(V,_.apply(0,Mn(G,!0))),D&&pr(V,P.apply(0,Mn(D,!0))),V},V=>{const[q]=V("update.ignoreMutation"),[G,D]=V("update.attributes"),[L,W]=V("update.elementEvents"),[Y,ae]=V("update.debounce"),ye=W||D,ue=X=>Os(q)&&q(X);if(ye&&(s&&(s[1](),s[0]()),s=WS(d||c,!0,P,{Ht:y.concat(G||[]),Dt:L,Mt:VS,kt:(X,K)=>{const{target:U,attributeName:se}=X;return(!K&&se&&!h?wW(U,VS,wV):!1)||!!Yl(U,`.${Io}`)||!!ue(X)}})),ae)if(S.m(),Rs(Y)){const X=Y[0],K=Y[1];r=pi(X)&&X,o=pi(K)&&K}else pi(Y)?(r=Y,o=!1):(r=!1,o=!1)}]},GS={x:0,y:0},CV=e=>({K:{t:0,r:0,b:0,l:0},St:!1,P:{marginRight:0,marginBottom:0,marginLeft:0,paddingTop:0,paddingRight:0,paddingBottom:0,paddingLeft:0},zt:GS,Tt:GS,Ct:{x:"hidden",y:"hidden"},Et:{x:!1,y:!1},ht:!1,bt:td(e.Z)}),kV=(e,t)=>{const n=t1(t,{}),[r,o,s]=Zb(),[a,c,d]=uV(e),p=G6(CV(a)),[h,m]=p,v=vV(a,p),b=(I,P,E)=>{const R=Bo(I).some(M=>I[M])||!qb(P)||E;return R&&s("u",[I,P,E]),R},[w,y,S,k]=SV(a,m,I=>b(v(n,I),{},!1)),_=h.bind(0);return _.jt=I=>r("u",I),_.Nt=()=>{const{W:I,J:P}=a,E=_s(I),O=Ca(I);y(),c(),_s(P,E),Ca(P,O)},_.qt=a,[(I,P)=>{const E=t1(t,I,P);return k(E),b(v(E,S(),P),I,!!P)},_,()=>{o(),w(),d()}]},{round:qS}=Math,_V=e=>{const{width:t,height:n}=Zs(e),{w:r,h:o}=nd(e);return{x:qS(t)/r||1,y:qS(n)/o||1}},PV=(e,t,n)=>{const r=t.scrollbars,{button:o,isPrimary:s,pointerType:a}=e,{pointers:c}=r;return o===0&&s&&r[n?"dragScroll":"clickScroll"]&&(c||[]).includes(a)},jV=(e,t)=>Dr(e,"mousedown",Dr.bind(0,t,"click",D6,{C:!0,$:!0}),{$:!0}),KS="pointerup pointerleave pointercancel lostpointercapture",IV=(e,t,n,r,o,s,a)=>{const{B:c}=Eo(),{Ft:d,Gt:p,Xt:h}=r,m=`scroll${a?"Left":"Top"}`,v=`client${a?"X":"Y"}`,b=a?"width":"height",w=a?"left":"top",y=a?"w":"h",S=a?"x":"y",k=(_,I)=>P=>{const{Tt:E}=s(),O=nd(p)[y]-nd(d)[y],M=I*P/O*E[S],A=td(h)&&a?c.n||c.i?1:-1:1;o[m]=_+M*A};return Dr(p,"pointerdown",_=>{const I=Yl(_.target,`.${ty}`)===d,P=I?d:p;if(Qi(t,ws,MS,!0),PV(_,e,I)){const E=!I&&_.shiftKey,O=()=>Zs(d),R=()=>Zs(p),M=(W,Y)=>(W||O())[w]-(Y||R())[w],T=k(o[m]||0,1/_V(o)[S]),A=_[v],$=O(),Q=R(),B=$[b],V=M($,Q)+B/2,q=A-Q[w],G=I?0:q-V,D=W=>{la(L),P.releasePointerCapture(W.pointerId)},L=[Qi.bind(0,t,ws,MS),Dr(n,KS,D),Dr(n,"selectstart",W=>T6(W),{S:!1}),Dr(p,KS,D),Dr(p,"pointermove",W=>{const Y=W[v]-A;(I||E)&&T(G+Y)})];if(E)T(G);else if(!I){const W=ll()[tV];W&&Mn(L,W.O(T,M,G,B,q))}P.setPointerCapture(_.pointerId)}})},EV=(e,t)=>(n,r,o,s,a,c)=>{const{Xt:d}=n,[p,h]=Ul(333),m=!!a.scrollBy;let v=!0;return la.bind(0,[Dr(d,"pointerenter",()=>{r(AS,!0)}),Dr(d,"pointerleave pointercancel",()=>{r(AS)}),Dr(d,"wheel",b=>{const{deltaX:w,deltaY:y,deltaMode:S}=b;m&&v&&S===0&&Ta(d)===s&&a.scrollBy({left:w,top:y,behavior:"smooth"}),v=!1,r(zS,!0),p(()=>{v=!0,r(zS)}),T6(b)},{S:!1,$:!0}),jV(d,o),IV(e,s,o,n,a,t,c),h])},{min:r1,max:YS,abs:OV,round:RV}=Math,Y6=(e,t,n,r)=>{if(r){const c=n?"x":"y",{Tt:d,zt:p}=r,h=p[c],m=d[c];return YS(0,r1(1,h/(h+m)))}const o=n?"width":"height",s=Zs(e)[o],a=Zs(t)[o];return YS(0,r1(1,s/a))},MV=(e,t,n,r,o,s)=>{const{B:a}=Eo(),c=s?"x":"y",d=s?"Left":"Top",{Tt:p}=r,h=RV(p[c]),m=OV(n[`scroll${d}`]),v=s&&o,b=a.i?m:h-m,y=r1(1,(v?b:m)/h),S=Y6(e,t,s);return 1/S*(1-S)*y},DV=(e,t,n)=>{const{N:r,L:o}=Eo(),{scrollbars:s}=r(),{slot:a}=s,{ct:c,W:d,Z:p,J:h,lt:m,ot:v,it:b,ut:w}=t,{scrollbars:y}=m?{}:e,{slot:S}=y||{},k=V6([d,p,h],()=>w&&b?d:p,a,S),_=(G,D,L)=>{const W=L?ka:Xb;_n(G,Y=>{W(Y.Xt,D)})},I=(G,D)=>{_n(G,L=>{const[W,Y]=D(L);ro(W,Y)})},P=(G,D,L)=>{I(G,W=>{const{Ft:Y,Gt:ae}=W;return[Y,{[L?"width":"height"]:`${(100*Y6(Y,ae,L,D)).toFixed(3)}%`}]})},E=(G,D,L)=>{const W=L?"X":"Y";I(G,Y=>{const{Ft:ae,Gt:ye,Xt:ue}=Y,X=MV(ae,ye,v,D,td(ue),L);return[ae,{transform:X===X?`translate${W}(${(100*X).toFixed(3)}%)`:""}]})},O=[],R=[],M=[],T=(G,D,L)=>{const W=Vb(L),Y=W?L:!0,ae=W?!L:!0;Y&&_(R,G,D),ae&&_(M,G,D)},A=G=>{P(R,G,!0),P(M,G)},$=G=>{E(R,G,!0),E(M,G)},Q=G=>{const D=G?GW:qW,L=G?R:M,W=Gb(L)?TS:"",Y=Ji(`${Io} ${D} ${W}`),ae=Ji(H6),ye=Ji(ty),ue={Xt:Y,Gt:ae,Ft:ye};return o||ka(Y,WW),ts(Y,ae),ts(ae,ye),Mn(L,ue),Mn(O,[oa.bind(0,Y),n(ue,T,c,p,v,G)]),ue},B=Q.bind(0,!0),V=Q.bind(0,!1),q=()=>{ts(k,R[0].Xt),ts(k,M[0].Xt),Jp(()=>{T(TS)},300)};return B(),V(),[{Ut:A,Wt:$,Zt:T,Jt:{Kt:R,Qt:B,tn:I.bind(0,R)},nn:{Kt:M,Qt:V,tn:I.bind(0,M)}},q,la.bind(0,O)]},TV=(e,t,n,r)=>{let o,s,a,c,d,p=0;const h=G6({}),[m]=h,[v,b]=Ul(),[w,y]=Ul(),[S,k]=Ul(100),[_,I]=Ul(100),[P,E]=Ul(()=>p),[O,R,M]=DV(e,n.qt,EV(t,n)),{Z:T,J:A,ot:$,st:Q,ut:B,it:V}=n.qt,{Jt:q,nn:G,Zt:D,Ut:L,Wt:W}=O,{tn:Y}=q,{tn:ae}=G,ye=se=>{const{Xt:re}=se,oe=B&&!V&&Ta(re)===A&&re;return[oe,{transform:oe?`translate(${_s($)}px, ${Ca($)}px)`:""}]},ue=(se,re)=>{if(E(),se)D($S);else{const oe=()=>D($S,!0);p>0&&!re?P(oe):oe()}},X=()=>{c=s,c&&ue(!0)},K=[k,E,I,y,b,M,Dr(T,"pointerover",X,{C:!0}),Dr(T,"pointerenter",X),Dr(T,"pointerleave",()=>{c=!1,s&&ue(!1)}),Dr(T,"pointermove",()=>{o&&v(()=>{k(),ue(!0),_(()=>{o&&ue(!1)})})}),Dr(Q,"scroll",se=>{w(()=>{W(n()),a&&ue(!0),S(()=>{a&&!c&&ue(!1)})}),r(se),B&&Y(ye),B&&ae(ye)})],U=m.bind(0);return U.qt=O,U.Nt=R,[(se,re,oe)=>{const{At:pe,Lt:le,It:ge,yt:_e}=oe,{A:ie}=Eo(),Se=t1(t,se,re),Fe=n(),{Tt:Ae,Ct:He,bt:Ct}=Fe,[ct,on]=Se("showNativeOverlaidScrollbars"),[vt,bt]=Se("scrollbars.theme"),[we,Re]=Se("scrollbars.visibility"),[Pt,At]=Se("scrollbars.autoHide"),[xe]=Se("scrollbars.autoHideDelay"),[ht,$t]=Se("scrollbars.dragScroll"),[zt,Ne]=Se("scrollbars.clickScroll"),qe=pe||le||_e,Pn=ge||Re,Pe=ct&&ie.x&&ie.y,Je=(Xe,dt)=>{const Lt=we==="visible"||we==="auto"&&Xe==="scroll";return D(KW,Lt,dt),Lt};if(p=xe,on&&D(VW,Pe),bt&&(D(d),D(vt,!0),d=vt),At&&(o=Pt==="move",s=Pt==="leave",a=Pt!=="never",ue(!a,!0)),$t&&D(QW,ht),Ne&&D(XW,zt),Pn){const Xe=Je(He.x,!0),dt=Je(He.y,!1);D(YW,!(Xe&&dt))}qe&&(L(Fe),W(Fe),D(NS,!Ae.x,!0),D(NS,!Ae.y,!1),D(UW,Ct&&!V))},U,la.bind(0,K)]},X6=(e,t,n)=>{Os(e)&&e(t||void 0,n||void 0)},ci=(e,t,n)=>{const{F:r,N:o,Y:s,j:a}=Eo(),c=ll(),d=Xp(e),p=d?e:e.target,h=U6(p);if(t&&!h){let m=!1;const v=B=>{const V=ll()[ZW],q=V&&V.O;return q?q(B,!0):B},b=pr({},r(),v(t)),[w,y,S]=Zb(n),[k,_,I]=kV(e,b),[P,E,O]=TV(e,b,_,B=>S("scroll",[Q,B])),R=(B,V)=>k(B,!!V),M=R.bind(0,{},!0),T=s(M),A=a(M),$=B=>{cV(p),T(),A(),O(),I(),m=!0,S("destroyed",[Q,!!B]),y()},Q={options(B,V){if(B){const q=V?r():{},G=A6(b,pr(q,v(B)));qb(G)||(pr(b,G),R(G))}return pr({},b)},on:w,off:(B,V)=>{B&&V&&y(B,V)},state(){const{zt:B,Tt:V,Ct:q,Et:G,K:D,St:L,bt:W}=_();return pr({},{overflowEdge:B,overflowAmount:V,overflowStyle:q,hasOverflow:G,padding:D,paddingAbsolute:L,directionRTL:W,destroyed:m})},elements(){const{W:B,Z:V,K:q,J:G,tt:D,ot:L,st:W}=_.qt,{Jt:Y,nn:ae}=E.qt,ye=X=>{const{Ft:K,Gt:U,Xt:se}=X;return{scrollbar:se,track:U,handle:K}},ue=X=>{const{Kt:K,Qt:U}=X,se=ye(K[0]);return pr({},se,{clone:()=>{const re=ye(U());return P({},!0,{}),re}})};return pr({},{target:B,host:V,padding:q||G,viewport:G,content:D||G,scrollOffsetElement:L,scrollEventElement:W,scrollbarHorizontal:ue(Y),scrollbarVertical:ue(ae)})},update:B=>R({},B),destroy:$.bind(0)};return _.jt((B,V,q)=>{P(V,q,B)}),lV(p,Q),_n(Bo(c),B=>X6(c[B],0,Q)),iV(_.qt.it,o().cancel,!d&&e.cancel)?($(!0),Q):(_.Nt(),E.Nt(),S("initialized",[Q]),_.jt((B,V,q)=>{const{gt:G,yt:D,vt:L,At:W,Lt:Y,It:ae,wt:ye,Ot:ue}=B;S("updated",[Q,{updateHints:{sizeChanged:G,directionChanged:D,heightIntrinsicChanged:L,overflowEdgeChanged:W,overflowAmountChanged:Y,overflowStyleChanged:ae,contentMutation:ye,hostMutation:ue},changedOptions:V,force:q}])}),Q.update(!0),Q)}return h};ci.plugin=e=>{_n(JW(e),t=>X6(t,ci))};ci.valid=e=>{const t=e&&e.elements,n=Os(t)&&t();return Xv(n)&&!!U6(n.target)};ci.env=()=>{const{k:e,A:t,I:n,B:r,V:o,L:s,X:a,U:c,N:d,q:p,F:h,G:m}=Eo();return pr({},{scrollbarsSize:e,scrollbarsOverlaid:t,scrollbarsHiding:n,rtlScrollBehavior:r,flexboxGlue:o,cssCustomProperties:s,staticDefaultInitialization:a,staticDefaultOptions:c,getDefaultInitialization:d,setDefaultInitialization:p,getDefaultOptions:h,setDefaultOptions:m})};const AV=()=>{if(typeof window>"u"){const p=()=>{};return[p,p]}let e,t;const n=window,r=typeof n.requestIdleCallback=="function",o=n.requestAnimationFrame,s=n.cancelAnimationFrame,a=r?n.requestIdleCallback:o,c=r?n.cancelIdleCallback:s,d=()=>{c(e),s(t)};return[(p,h)=>{d(),e=a(r?()=>{d(),t=o(p)}:p,typeof h=="object"?h:{timeout:2233})},d]},sy=e=>{const{options:t,events:n,defer:r}=e||{},[o,s]=f.useMemo(AV,[]),a=f.useRef(null),c=f.useRef(r),d=f.useRef(t),p=f.useRef(n);return f.useEffect(()=>{c.current=r},[r]),f.useEffect(()=>{const{current:h}=a;d.current=t,ci.valid(h)&&h.options(t||{},!0)},[t]),f.useEffect(()=>{const{current:h}=a;p.current=n,ci.valid(h)&&h.on(n||{},!0)},[n]),f.useEffect(()=>()=>{var h;s(),(h=a.current)==null||h.destroy()},[]),f.useMemo(()=>[h=>{const m=a.current;if(ci.valid(m))return;const v=c.current,b=d.current||{},w=p.current||{},y=()=>a.current=ci(h,b,w);v?o(y,v):y()},()=>a.current],[])},NV=(e,t)=>{const{element:n="div",options:r,events:o,defer:s,children:a,...c}=e,d=n,p=f.useRef(null),h=f.useRef(null),[m,v]=sy({options:r,events:o,defer:s});return f.useEffect(()=>{const{current:b}=p,{current:w}=h;return b&&w&&m({target:b,elements:{viewport:w,content:w}}),()=>{var y;return(y=v())==null?void 0:y.destroy()}},[m,n]),f.useImperativeHandle(t,()=>({osInstance:v,getElement:()=>p.current}),[]),F.createElement(d,{"data-overlayscrollbars-initialize":"",ref:p,...c},F.createElement("div",{ref:h},a))},Q6=f.forwardRef(NV);var J6={exports:{}},Z6={};const No=T1(IR),pu=T1(ER),$V=T1(OR);(function(e){var t,n,r=Rl&&Rl.__generator||function(J,ee){var he,ke,me,ut,st={label:0,sent:function(){if(1&me[0])throw me[1];return me[1]},trys:[],ops:[]};return ut={next:Ft(0),throw:Ft(1),return:Ft(2)},typeof Symbol=="function"&&(ut[Symbol.iterator]=function(){return this}),ut;function Ft(ft){return function(xt){return function(Be){if(he)throw new TypeError("Generator is already executing.");for(;st;)try{if(he=1,ke&&(me=2&Be[0]?ke.return:Be[0]?ke.throw||((me=ke.return)&&me.call(ke),0):ke.next)&&!(me=me.call(ke,Be[1])).done)return me;switch(ke=0,me&&(Be=[2&Be[0],me.value]),Be[0]){case 0:case 1:me=Be;break;case 4:return st.label++,{value:Be[1],done:!1};case 5:st.label++,ke=Be[1],Be=[0];continue;case 7:Be=st.ops.pop(),st.trys.pop();continue;default:if(!((me=(me=st.trys).length>0&&me[me.length-1])||Be[0]!==6&&Be[0]!==2)){st=0;continue}if(Be[0]===3&&(!me||Be[1]>me[0]&&Be[1]=200&&J.status<=299},Q=function(J){return/ion\/(vnd\.api\+)?json/.test(J.get("content-type")||"")};function B(J){if(!(0,T.isPlainObject)(J))return J;for(var ee=S({},J),he=0,ke=Object.entries(ee);he"u"&&st===A&&console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments."),function(Jt,Vt){return E(ee,null,function(){var $e,yt,Mt,Ht,jn,Ut,un,sn,Ir,Qn,It,In,On,Jn,hr,Tn,An,dn,Sn,En,vn,bn,Ke,Ot,St,at,wt,Bt,mt,ot,Ee,je,Me,We,Ze,Dt;return r(this,function(Rt){switch(Rt.label){case 0:return $e=Vt.signal,yt=Vt.getState,Mt=Vt.extra,Ht=Vt.endpoint,jn=Vt.forced,Ut=Vt.type,Ir=(sn=typeof Jt=="string"?{url:Jt}:Jt).url,It=(Qn=sn.headers)===void 0?new Headers(Gt.headers):Qn,On=(In=sn.params)===void 0?void 0:In,hr=(Jn=sn.responseHandler)===void 0?Et??"json":Jn,An=(Tn=sn.validateStatus)===void 0?Nt??$:Tn,Sn=(dn=sn.timeout)===void 0?jt:dn,En=I(sn,["url","headers","params","responseHandler","validateStatus","timeout"]),vn=S(k(S({},Gt),{signal:$e}),En),It=new Headers(B(It)),bn=vn,[4,me(It,{getState:yt,extra:Mt,endpoint:Ht,forced:jn,type:Ut})];case 1:bn.headers=Rt.sent()||It,Ke=function(Ve){return typeof Ve=="object"&&((0,T.isPlainObject)(Ve)||Array.isArray(Ve)||typeof Ve.toJSON=="function")},!vn.headers.has("content-type")&&Ke(vn.body)&&vn.headers.set("content-type",Ce),Ke(vn.body)&&xt(vn.headers)&&(vn.body=JSON.stringify(vn.body,Qe)),On&&(Ot=~Ir.indexOf("?")?"&":"?",St=Ft?Ft(On):new URLSearchParams(B(On)),Ir+=Ot+St),Ir=function(Ve,en){if(!Ve)return en;if(!en)return Ve;if(function(hn){return new RegExp("(^|:)//").test(hn)}(en))return en;var yn=Ve.endsWith("/")||!en.startsWith("?")?"/":"";return Ve=function(hn){return hn.replace(/\/$/,"")}(Ve),""+Ve+yn+function(hn){return hn.replace(/^\//,"")}(en)}(he,Ir),at=new Request(Ir,vn),wt=at.clone(),un={request:wt},mt=!1,ot=Sn&&setTimeout(function(){mt=!0,Vt.abort()},Sn),Rt.label=2;case 2:return Rt.trys.push([2,4,5,6]),[4,st(at)];case 3:return Bt=Rt.sent(),[3,6];case 4:return Ee=Rt.sent(),[2,{error:{status:mt?"TIMEOUT_ERROR":"FETCH_ERROR",error:String(Ee)},meta:un}];case 5:return ot&&clearTimeout(ot),[7];case 6:je=Bt.clone(),un.response=je,We="",Rt.label=7;case 7:return Rt.trys.push([7,9,,10]),[4,Promise.all([Zt(Bt,hr).then(function(Ve){return Me=Ve},function(Ve){return Ze=Ve}),je.text().then(function(Ve){return We=Ve},function(){})])];case 8:if(Rt.sent(),Ze)throw Ze;return[3,10];case 9:return Dt=Rt.sent(),[2,{error:{status:"PARSING_ERROR",originalStatus:Bt.status,data:We,error:String(Dt)},meta:un}];case 10:return[2,An(Bt,Me)?{data:Me,meta:un}:{error:{status:Bt.status,data:Me},meta:un}]}})})};function Zt(Jt,Vt){return E(this,null,function(){var $e;return r(this,function(yt){switch(yt.label){case 0:return typeof Vt=="function"?[2,Vt(Jt)]:(Vt==="content-type"&&(Vt=xt(Jt.headers)?"json":"text"),Vt!=="json"?[3,2]:[4,Jt.text()]);case 1:return[2,($e=yt.sent()).length?JSON.parse($e):null];case 2:return[2,Jt.text()]}})})}}var q=function(J,ee){ee===void 0&&(ee=void 0),this.value=J,this.meta=ee};function G(J,ee){return J===void 0&&(J=0),ee===void 0&&(ee=5),E(this,null,function(){var he,ke;return r(this,function(me){switch(me.label){case 0:return he=Math.min(J,ee),ke=~~((Math.random()+.4)*(300<=je)}var En=(0,He.createAsyncThunk)(On+"/executeQuery",dn,{getPendingMeta:function(){var Ke;return(Ke={startedTimeStamp:Date.now()})[He.SHOULD_AUTOBATCH]=!0,Ke},condition:function(Ke,Ot){var St,at,wt,Bt=(0,Ot.getState)(),mt=(at=(St=Bt[On])==null?void 0:St.queries)==null?void 0:at[Ke.queryCacheKey],ot=mt==null?void 0:mt.fulfilledTimeStamp,Ee=Ke.originalArgs,je=mt==null?void 0:mt.originalArgs,Me=hr[Ke.endpointName];return!(!Se(Ke)&&((mt==null?void 0:mt.status)==="pending"||!Sn(Ke,Bt)&&(!oe(Me)||!((wt=Me==null?void 0:Me.forceRefetch)!=null&&wt.call(Me,{currentArg:Ee,previousArg:je,endpointState:mt,state:Bt})))&&ot))},dispatchConditionRejection:!0}),vn=(0,He.createAsyncThunk)(On+"/executeMutation",dn,{getPendingMeta:function(){var Ke;return(Ke={startedTimeStamp:Date.now()})[He.SHOULD_AUTOBATCH]=!0,Ke}});function bn(Ke){return function(Ot){var St,at;return((at=(St=Ot==null?void 0:Ot.meta)==null?void 0:St.arg)==null?void 0:at.endpointName)===Ke}}return{queryThunk:En,mutationThunk:vn,prefetch:function(Ke,Ot,St){return function(at,wt){var Bt=function(Me){return"force"in Me}(St)&&St.force,mt=function(Me){return"ifOlderThan"in Me}(St)&&St.ifOlderThan,ot=function(Me){return Me===void 0&&(Me=!0),An.endpoints[Ke].initiate(Ot,{forceRefetch:Me})},Ee=An.endpoints[Ke].select(Ot)(wt());if(Bt)at(ot());else if(mt){var je=Ee==null?void 0:Ee.fulfilledTimeStamp;if(!je)return void at(ot());(Number(new Date)-Number(new Date(je)))/1e3>=mt&&at(ot())}else at(ot(!1))}},updateQueryData:function(Ke,Ot,St){return function(at,wt){var Bt,mt,ot=An.endpoints[Ke].select(Ot)(wt()),Ee={patches:[],inversePatches:[],undo:function(){return at(An.util.patchQueryData(Ke,Ot,Ee.inversePatches))}};if(ot.status===t.uninitialized)return Ee;if("data"in ot)if((0,Ae.isDraftable)(ot.data)){var je=(0,Ae.produceWithPatches)(ot.data,St),Me=je[2];(Bt=Ee.patches).push.apply(Bt,je[1]),(mt=Ee.inversePatches).push.apply(mt,Me)}else{var We=St(ot.data);Ee.patches.push({op:"replace",path:[],value:We}),Ee.inversePatches.push({op:"replace",path:[],value:ot.data})}return at(An.util.patchQueryData(Ke,Ot,Ee.patches)),Ee}},upsertQueryData:function(Ke,Ot,St){return function(at){var wt;return at(An.endpoints[Ke].initiate(Ot,((wt={subscribe:!1,forceRefetch:!0})[ie]=function(){return{data:St}},wt)))}},patchQueryData:function(Ke,Ot,St){return function(at){at(An.internalActions.queryResultPatched({queryCacheKey:Tn({queryArgs:Ot,endpointDefinition:hr[Ke],endpointName:Ke}),patches:St}))}},buildMatchThunkActions:function(Ke,Ot){return{matchPending:(0,Fe.isAllOf)((0,Fe.isPending)(Ke),bn(Ot)),matchFulfilled:(0,Fe.isAllOf)((0,Fe.isFulfilled)(Ke),bn(Ot)),matchRejected:(0,Fe.isAllOf)((0,Fe.isRejected)(Ke),bn(Ot))}}}}({baseQuery:ke,reducerPath:me,context:he,api:J,serializeQueryArgs:ut}),Qe=Ce.queryThunk,jt=Ce.mutationThunk,Et=Ce.patchQueryData,Nt=Ce.updateQueryData,Gt=Ce.upsertQueryData,Zt=Ce.prefetch,Jt=Ce.buildMatchThunkActions,Vt=function(It){var In=It.reducerPath,On=It.queryThunk,Jn=It.mutationThunk,hr=It.context,Tn=hr.endpointDefinitions,An=hr.apiUid,dn=hr.extractRehydrationInfo,Sn=hr.hasRehydrationInfo,En=It.assertTagType,vn=It.config,bn=(0,ge.createAction)(In+"/resetApiState"),Ke=(0,ge.createSlice)({name:In+"/queries",initialState:Pt,reducers:{removeQueryResult:{reducer:function(ot,Ee){delete ot[Ee.payload.queryCacheKey]},prepare:(0,ge.prepareAutoBatched)()},queryResultPatched:function(ot,Ee){var je=Ee.payload,Me=je.patches;bt(ot,je.queryCacheKey,function(We){We.data=(0,vt.applyPatches)(We.data,Me.concat())})}},extraReducers:function(ot){ot.addCase(On.pending,function(Ee,je){var Me,We=je.meta,Ze=je.meta.arg,Dt=Se(Ze);(Ze.subscribe||Dt)&&(Ee[Me=Ze.queryCacheKey]!=null||(Ee[Me]={status:t.uninitialized,endpointName:Ze.endpointName})),bt(Ee,Ze.queryCacheKey,function(Rt){Rt.status=t.pending,Rt.requestId=Dt&&Rt.requestId?Rt.requestId:We.requestId,Ze.originalArgs!==void 0&&(Rt.originalArgs=Ze.originalArgs),Rt.startedTimeStamp=We.startedTimeStamp})}).addCase(On.fulfilled,function(Ee,je){var Me=je.meta,We=je.payload;bt(Ee,Me.arg.queryCacheKey,function(Ze){var Dt;if(Ze.requestId===Me.requestId||Se(Me.arg)){var Rt=Tn[Me.arg.endpointName].merge;if(Ze.status=t.fulfilled,Rt)if(Ze.data!==void 0){var Ve=Me.fulfilledTimeStamp,en=Me.arg,yn=Me.baseQueryMeta,hn=Me.requestId,mr=(0,ge.createNextState)(Ze.data,function(Yn){return Rt(Yn,We,{arg:en.originalArgs,baseQueryMeta:yn,fulfilledTimeStamp:Ve,requestId:hn})});Ze.data=mr}else Ze.data=We;else Ze.data=(Dt=Tn[Me.arg.endpointName].structuralSharing)==null||Dt?M((0,on.isDraft)(Ze.data)?(0,vt.original)(Ze.data):Ze.data,We):We;delete Ze.error,Ze.fulfilledTimeStamp=Me.fulfilledTimeStamp}})}).addCase(On.rejected,function(Ee,je){var Me=je.meta,We=Me.condition,Ze=Me.requestId,Dt=je.error,Rt=je.payload;bt(Ee,Me.arg.queryCacheKey,function(Ve){if(!We){if(Ve.requestId!==Ze)return;Ve.status=t.rejected,Ve.error=Rt??Dt}})}).addMatcher(Sn,function(Ee,je){for(var Me=dn(je).queries,We=0,Ze=Object.entries(Me);We"u"||navigator.onLine===void 0||navigator.onLine,focused:typeof document>"u"||document.visibilityState!=="hidden",middlewareRegistered:!1},vn),reducers:{middlewareRegistered:function(ot,Ee){ot.middlewareRegistered=ot.middlewareRegistered!=="conflict"&&An===Ee.payload||"conflict"}},extraReducers:function(ot){ot.addCase(ye,function(Ee){Ee.online=!0}).addCase(ue,function(Ee){Ee.online=!1}).addCase(Y,function(Ee){Ee.focused=!0}).addCase(ae,function(Ee){Ee.focused=!1}).addMatcher(Sn,function(Ee){return S({},Ee)})}}),mt=(0,ge.combineReducers)({queries:Ke.reducer,mutations:Ot.reducer,provided:St.reducer,subscriptions:wt.reducer,config:Bt.reducer});return{reducer:function(ot,Ee){return mt(bn.match(Ee)?void 0:ot,Ee)},actions:k(S(S(S(S(S({},Bt.actions),Ke.actions),at.actions),wt.actions),Ot.actions),{unsubscribeMutationResult:Ot.actions.removeMutationResult,resetApiState:bn})}}({context:he,queryThunk:Qe,mutationThunk:jt,reducerPath:me,assertTagType:Be,config:{refetchOnFocus:ft,refetchOnReconnect:xt,refetchOnMountOrArgChange:Ft,keepUnusedDataFor:st,reducerPath:me}}),$e=Vt.reducer,yt=Vt.actions;Nr(J.util,{patchQueryData:Et,updateQueryData:Nt,upsertQueryData:Gt,prefetch:Zt,resetApiState:yt.resetApiState}),Nr(J.internalActions,yt);var Mt=function(It){var In=It.reducerPath,On=It.queryThunk,Jn=It.api,hr=It.context,Tn=hr.apiUid,An={invalidateTags:(0,lr.createAction)(In+"/invalidateTags")},dn=[Hr,pn,Fr,br,Wn,Ro];return{middleware:function(En){var vn=!1,bn=k(S({},It),{internalState:{currentSubscriptions:{}},refetchQuery:Sn}),Ke=dn.map(function(at){return at(bn)}),Ot=function(at){var wt=at.api,Bt=at.queryThunk,mt=at.internalState,ot=wt.reducerPath+"/subscriptions",Ee=null,je=!1,Me=wt.internalActions,We=Me.updateSubscriptionOptions,Ze=Me.unsubscribeQueryResult;return function(Dt,Rt){var Ve,en;if(Ee||(Ee=JSON.parse(JSON.stringify(mt.currentSubscriptions))),wt.util.resetApiState.match(Dt))return Ee=mt.currentSubscriptions={},[!0,!1];if(wt.internalActions.internal_probeSubscription.match(Dt)){var yn=Dt.payload;return[!1,!!((Ve=mt.currentSubscriptions[yn.queryCacheKey])!=null&&Ve[yn.requestId])]}var hn=function(gn,Vn){var ao,fn,Nn,Vr,Er,Va,Vd,Mo,da;if(We.match(Vn)){var Ls=Vn.payload,fa=Ls.queryCacheKey,io=Ls.requestId;return(ao=gn==null?void 0:gn[fa])!=null&&ao[io]&&(gn[fa][io]=Ls.options),!0}if(Ze.match(Vn)){var lo=Vn.payload;return io=lo.requestId,gn[fa=lo.queryCacheKey]&&delete gn[fa][io],!0}if(wt.internalActions.removeQueryResult.match(Vn))return delete gn[Vn.payload.queryCacheKey],!0;if(Bt.pending.match(Vn)){var co=Vn.meta;if(io=co.requestId,(Qr=co.arg).subscribe)return(Ho=(Nn=gn[fn=Qr.queryCacheKey])!=null?Nn:gn[fn]={})[io]=(Er=(Vr=Qr.subscriptionOptions)!=null?Vr:Ho[io])!=null?Er:{},!0}if(Bt.rejected.match(Vn)){var Ho,Do=Vn.meta,Qr=Do.arg;if(io=Do.requestId,Do.condition&&Qr.subscribe)return(Ho=(Vd=gn[Va=Qr.queryCacheKey])!=null?Vd:gn[Va]={})[io]=(da=(Mo=Qr.subscriptionOptions)!=null?Mo:Ho[io])!=null?da:{},!0}return!1}(mt.currentSubscriptions,Dt);if(hn){je||(fs(function(){var gn=JSON.parse(JSON.stringify(mt.currentSubscriptions)),Vn=(0,Wr.produceWithPatches)(Ee,function(){return gn});Rt.next(wt.internalActions.subscriptionsUpdated(Vn[1])),Ee=gn,je=!1}),je=!0);var mr=!!((en=Dt.type)!=null&&en.startsWith(ot)),Yn=Bt.rejected.match(Dt)&&Dt.meta.condition&&!!Dt.meta.arg.subscribe;return[!mr&&!Yn,!1]}return[!0,!1]}}(bn),St=function(at){var wt=at.reducerPath,Bt=at.context,mt=at.refetchQuery,ot=at.internalState,Ee=at.api.internalActions.removeQueryResult;function je(Me,We){var Ze=Me.getState()[wt],Dt=Ze.queries,Rt=ot.currentSubscriptions;Bt.batch(function(){for(var Ve=0,en=Object.keys(Rt);Ve{const{imageUsage:t,topMessage:n="This image is currently in use in the following features:",bottomMessage:r="If you delete this image, those features will immediately be reset."}=e;return!t||!xu(t)?null:i.jsxs(i.Fragment,{children:[i.jsx(tt,{children:n}),i.jsxs(vb,{sx:{paddingInlineStart:6},children:[t.isInitialImage&&i.jsx(xa,{children:"Image to Image"}),t.isCanvasImage&&i.jsx(xa,{children:"Unified Canvas"}),t.isControlNetImage&&i.jsx(xa,{children:"ControlNet"}),t.isNodesImage&&i.jsx(xa,{children:"Node Editor"})]}),i.jsx(tt,{children:r})]})},ej=f.memo(zV),LV=e=>{const{boardToDelete:t,setBoardToDelete:n}=e,{t:r}=be(),o=z(_=>_.config.canRestoreDeletedImagesFromBin),{currentData:s,isFetching:a}=RR((t==null?void 0:t.board_id)??oo.skipToken),c=f.useMemo(()=>fe([Ye],_=>{const I=(s??[]).map(E=>MR(_,E));return{imageUsageSummary:{isInitialImage:xu(I,E=>E.isInitialImage),isCanvasImage:xu(I,E=>E.isCanvasImage),isNodesImage:xu(I,E=>E.isNodesImage),isControlNetImage:xu(I,E=>E.isControlNetImage)}}}),[s]),[d,{isLoading:p}]=DR(),[h,{isLoading:m}]=TR(),{imageUsageSummary:v}=z(c),b=f.useCallback(()=>{t&&(d(t.board_id),n(void 0))},[t,d,n]),w=f.useCallback(()=>{t&&(h(t.board_id),n(void 0))},[t,h,n]),y=f.useCallback(()=>{n(void 0)},[n]),S=f.useRef(null),k=f.useMemo(()=>m||p||a,[m,p,a]);return t?i.jsx(Pd,{isOpen:!!t,onClose:y,leastDestructiveRef:S,isCentered:!0,children:i.jsx(Ma,{children:i.jsxs(jd,{children:[i.jsxs(Ra,{fontSize:"lg",fontWeight:"bold",children:["Delete ",t.board_name]}),i.jsx(Da,{children:i.jsxs(H,{direction:"column",gap:3,children:[a?i.jsx(gm,{children:i.jsx(H,{sx:{w:"full",h:32}})}):i.jsx(ej,{imageUsage:v,topMessage:"This board contains images used in the following features:",bottomMessage:"Deleting this board and its images will reset any features currently using them."}),i.jsx(tt,{children:"Deleted boards cannot be restored."}),i.jsx(tt,{children:r(o?"gallery.deleteImageBin":"gallery.deleteImagePermanent")})]})}),i.jsx(Oa,{children:i.jsxs(H,{sx:{justifyContent:"space-between",width:"full",gap:2},children:[i.jsx(rn,{ref:S,onClick:y,children:"Cancel"}),i.jsx(rn,{colorScheme:"warning",isLoading:k,onClick:b,children:"Delete Board Only"}),i.jsx(rn,{colorScheme:"error",isLoading:k,onClick:w,children:"Delete Board and Images"})]})})]})})}):null},BV=f.memo(LV),tj=Te((e,t)=>{const{role:n,tooltip:r="",tooltipProps:o,isChecked:s,...a}=e;return i.jsx(wn,{label:r,hasArrow:!0,...o,...o!=null&&o.placement?{placement:o.placement}:{placement:"top"},children:i.jsx(Sa,{ref:t,role:n,colorScheme:s?"accent":"base",...a})})});tj.displayName="IAIIconButton";const Le=f.memo(tj),FV="My Board",HV=()=>{const[e,{isLoading:t}]=AR(),n=f.useCallback(()=>{e(FV)},[e]);return i.jsx(Le,{icon:i.jsx(ml,{}),isLoading:t,tooltip:"Add Board","aria-label":"Add Board",onClick:n,size:"sm"})};var nj=md({displayName:"ExternalLinkIcon",path:i.jsxs("g",{fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2",children:[i.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),i.jsx("path",{d:"M15 3h6v6"}),i.jsx("path",{d:"M10 14L21 3"})]})}),ay=md({d:"M12 8l-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14z",displayName:"ChevronUpIcon"}),WV=md({displayName:"CloseIcon",d:"M.439,21.44a1.5,1.5,0,0,0,2.122,2.121L11.823,14.3a.25.25,0,0,1,.354,0l9.262,9.263a1.5,1.5,0,1,0,2.122-2.121L14.3,12.177a.25.25,0,0,1,0-.354l9.263-9.262A1.5,1.5,0,0,0,21.439.44L12.177,9.7a.25.25,0,0,1-.354,0L2.561.44A1.5,1.5,0,0,0,.439,2.561L9.7,11.823a.25.25,0,0,1,0,.354Z"}),VV=md({displayName:"DeleteIcon",path:i.jsx("g",{fill:"currentColor",children:i.jsx("path",{d:"M19.452 7.5H4.547a.5.5 0 00-.5.545l1.287 14.136A2 2 0 007.326 24h9.347a2 2 0 001.992-1.819L19.95 8.045a.5.5 0 00-.129-.382.5.5 0 00-.369-.163zm-9.2 13a.75.75 0 01-1.5 0v-9a.75.75 0 011.5 0zm5 0a.75.75 0 01-1.5 0v-9a.75.75 0 011.5 0zM22 4h-4.75a.25.25 0 01-.25-.25V2.5A2.5 2.5 0 0014.5 0h-5A2.5 2.5 0 007 2.5v1.25a.25.25 0 01-.25.25H2a1 1 0 000 2h20a1 1 0 000-2zM9 3.75V2.5a.5.5 0 01.5-.5h5a.5.5 0 01.5.5v1.25a.25.25 0 01-.25.25h-5.5A.25.25 0 019 3.75z"})})}),UV=md({displayName:"ChevronDownIcon",d:"M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"});const GV=fe([Ye],({boards:e})=>{const{searchText:t}=e;return{searchText:t}},Ge),qV=()=>{const e=te(),{searchText:t}=z(GV),n=f.useRef(null),r=f.useCallback(c=>{e(O2(c))},[e]),o=f.useCallback(()=>{e(O2(""))},[e]),s=f.useCallback(c=>{c.key==="Escape"&&o()},[o]),a=f.useCallback(c=>{r(c.target.value)},[r]);return f.useEffect(()=>{n.current&&n.current.focus()},[]),i.jsxs(LP,{children:[i.jsx(yd,{ref:n,placeholder:"Search Boards...",value:t,onKeyDown:s,onChange:a}),t&&t.length&&i.jsx(hb,{children:i.jsx(Sa,{onClick:o,size:"xs",variant:"ghost","aria-label":"Clear Search",opacity:.5,icon:i.jsx(WV,{boxSize:2})})})]})},KV=f.memo(qV),YV=e=>{const{isOver:t,label:n="Drop"}=e,r=f.useRef(ui()),{colorMode:o}=Ds();return i.jsx(Xr.div,{initial:{opacity:0},animate:{opacity:1,transition:{duration:.1}},exit:{opacity:0,transition:{duration:.1}},children:i.jsxs(H,{sx:{position:"absolute",top:0,insetInlineStart:0,w:"full",h:"full"},children:[i.jsx(H,{sx:{position:"absolute",top:0,insetInlineStart:0,w:"full",h:"full",bg:ze("base.700","base.900")(o),opacity:.7,borderRadius:"base",alignItems:"center",justifyContent:"center",transitionProperty:"common",transitionDuration:"0.1s"}}),i.jsx(H,{sx:{position:"absolute",top:.5,insetInlineStart:.5,insetInlineEnd:.5,bottom:.5,opacity:1,borderWidth:2,borderColor:t?ze("base.50","base.50")(o):ze("base.200","base.300")(o),borderRadius:"lg",borderStyle:"dashed",transitionProperty:"common",transitionDuration:"0.1s",alignItems:"center",justifyContent:"center"},children:i.jsx(tt,{sx:{fontSize:"2xl",fontWeight:600,transform:t?"scale(1.1)":"scale(1)",color:t?ze("base.50","base.50")(o):ze("base.200","base.300")(o),transitionProperty:"common",transitionDuration:"0.1s"},children:n})})]})},r.current)},nh=f.memo(YV),XV=e=>{const{dropLabel:t,data:n,disabled:r}=e,o=f.useRef(ui()),{isOver:s,setNodeRef:a,active:c}=A1({id:o.current,disabled:r,data:n});return i.jsx(Oe,{ref:a,position:"absolute",top:0,insetInlineStart:0,w:"full",h:"full",pointerEvents:"none",children:i.jsx(Fo,{children:Ep(n,c)&&i.jsx(nh,{isOver:s,label:t})})})},iy=f.memo(XV),ly=({isSelected:e,isHovered:t})=>i.jsx(Oe,{className:"selection-box",sx:{position:"absolute",top:0,insetInlineEnd:0,bottom:0,insetInlineStart:0,borderRadius:"base",opacity:e?1:.7,transitionProperty:"common",transitionDuration:"0.1s",shadow:e?t?"hoverSelected.light":"selected.light":t?"hoverUnselected.light":void 0,_dark:{shadow:e?t?"hoverSelected.dark":"selected.dark":t?"hoverUnselected.dark":void 0}}}),rj=()=>i.jsx(H,{sx:{position:"absolute",insetInlineEnd:0,top:0,p:1},children:i.jsx(pl,{variant:"solid",sx:{bg:"accent.400",_dark:{bg:"accent.500"}},children:"auto"})});var Nu=globalThis&&globalThis.__assign||function(){return Nu=Object.assign||function(e){for(var t,n=1,r=arguments.length;n{const{boardName:t}=Zh(void 0,{selectFromResult:({data:n})=>{const r=n==null?void 0:n.find(s=>s.board_id===e);return{boardName:(r==null?void 0:r.board_name)||"Uncategorized"}}});return t},QV=({board:e,setBoardToDelete:t})=>{const n=f.useCallback(()=>{t&&t(e)},[e,t]);return i.jsxs(i.Fragment,{children:[e.image_count>0&&i.jsx(i.Fragment,{}),i.jsx(_r,{sx:{color:"error.600",_dark:{color:"error.300"}},icon:i.jsx(us,{}),onClick:n,children:"Delete Board"})]})},JV=f.memo(QV),ZV=()=>i.jsx(i.Fragment,{}),eU=f.memo(ZV),cy=f.memo(({board:e,board_id:t,setBoardToDelete:n,children:r})=>{const o=te(),s=f.useMemo(()=>fe(Ye,({gallery:h})=>({isAutoAdd:h.autoAddBoardId===t})),[t]),{isAutoAdd:a}=z(s),c=Rm(t),d=f.useCallback(()=>{o(O_(t))},[t,o]),p=f.useCallback(h=>{h.preventDefault()},[]);return i.jsx(oj,{menuProps:{size:"sm",isLazy:!0},menuButtonProps:{bg:"transparent",_hover:{bg:"transparent"}},renderMenu:()=>i.jsx(zc,{sx:{visibility:"visible !important"},motionProps:nm,onContextMenu:p,children:i.jsxs(Xu,{title:c,children:[i.jsx(_r,{icon:i.jsx(ml,{}),isDisabled:a,onClick:d,children:"Auto-add to this Board"}),!e&&i.jsx(eU,{}),e&&i.jsx(JV,{board:e,setBoardToDelete:n})]})}),children:r})});cy.displayName="HoverableBoard";const sj=f.memo(({board:e,isSelected:t,setBoardToDelete:n})=>{const r=te(),o=f.useMemo(()=>fe(Ye,({gallery:E})=>({isSelectedForAutoAdd:e.board_id===E.autoAddBoardId}),Ge),[e.board_id]),{isSelectedForAutoAdd:s}=z(o),[a,c]=f.useState(!1),d=f.useCallback(()=>{c(!0)},[]),p=f.useCallback(()=>{c(!1)},[]),{currentData:h}=os(e.cover_image_name??oo.skipToken),{board_name:m,board_id:v}=e,[b,w]=f.useState(m),y=f.useCallback(()=>{r(R_(v))},[v,r]),[S,{isLoading:k}]=NR(),_=f.useMemo(()=>({id:v,actionType:"MOVE_BOARD",context:{boardId:v}}),[v]),I=f.useCallback(async E=>{if(!E.trim()){w(m);return}if(E!==m)try{const{board_name:O}=await S({board_id:v,changes:{board_name:E}}).unwrap();w(O)}catch{w(m)}},[v,m,S]),P=f.useCallback(E=>{w(E)},[]);return i.jsx(Oe,{sx:{w:"full",h:"full",touchAction:"none",userSelect:"none"},children:i.jsx(H,{onMouseOver:d,onMouseOut:p,sx:{position:"relative",justifyContent:"center",alignItems:"center",aspectRatio:"1/1",w:"full",h:"full"},children:i.jsx(cy,{board:e,board_id:v,setBoardToDelete:n,children:E=>i.jsxs(H,{ref:E,onClick:y,sx:{w:"full",h:"full",position:"relative",justifyContent:"center",alignItems:"center",borderRadius:"base",cursor:"pointer",bg:"base.200",_dark:{bg:"base.800"}},children:[h!=null&&h.thumbnail_url?i.jsx(Tc,{src:h==null?void 0:h.thumbnail_url,draggable:!1,sx:{objectFit:"cover",w:"full",h:"full",maxH:"full",borderRadius:"base",borderBottomRadius:"lg"}}):i.jsx(H,{sx:{w:"full",h:"full",justifyContent:"center",alignItems:"center"},children:i.jsx(Kr,{boxSize:12,as:gW,sx:{mt:-6,opacity:.7,color:"base.500",_dark:{color:"base.500"}}})}),s&&i.jsx(rj,{}),i.jsx(ly,{isSelected:t,isHovered:a}),i.jsx(H,{sx:{position:"absolute",bottom:0,left:0,p:1,justifyContent:"center",alignItems:"center",w:"full",maxW:"full",borderBottomRadius:"base",bg:t?"accent.400":"base.500",color:t?"base.50":"base.100",_dark:{bg:t?"accent.500":"base.600",color:t?"base.50":"base.100"},lineHeight:"short",fontSize:"xs"},children:i.jsxs(J3,{value:b,isDisabled:k,submitOnBlur:!0,onChange:P,onSubmit:I,sx:{w:"full"},children:[i.jsx(Y3,{sx:{p:0,fontWeight:t?700:500,textAlign:"center",overflow:"hidden",textOverflow:"ellipsis"},noOfLines:1}),i.jsx(K3,{sx:{p:0,_focusVisible:{p:0,textAlign:"center",boxShadow:"none"}}})]})}),i.jsx(iy,{data:_,dropLabel:i.jsx(tt,{fontSize:"md",children:"Move"})})]})})})})});sj.displayName="HoverableBoard";const tU=fe(Ye,({gallery:e})=>{const{autoAddBoardId:t}=e;return{autoAddBoardId:t}},Ge),aj=f.memo(({isSelected:e})=>{const t=te(),{autoAddBoardId:n}=z(tU),r=Rm(void 0),o=f.useCallback(()=>{t(R_(void 0))},[t]),[s,a]=f.useState(!1),c=f.useCallback(()=>{a(!0)},[]),d=f.useCallback(()=>{a(!1)},[]),p=f.useMemo(()=>({id:"no_board",actionType:"MOVE_BOARD",context:{boardId:void 0}}),[]);return i.jsx(Oe,{sx:{w:"full",h:"full",touchAction:"none",userSelect:"none"},children:i.jsx(H,{onMouseOver:c,onMouseOut:d,sx:{position:"relative",justifyContent:"center",alignItems:"center",aspectRatio:"1/1",borderRadius:"base",w:"full",h:"full"},children:i.jsx(cy,{children:h=>i.jsxs(H,{ref:h,onClick:o,sx:{w:"full",h:"full",position:"relative",justifyContent:"center",alignItems:"center",borderRadius:"base",cursor:"pointer",bg:"base.200",_dark:{bg:"base.800"}},children:[i.jsx(H,{sx:{w:"full",h:"full",justifyContent:"center",alignItems:"center"},children:i.jsx(Tc,{src:M_,alt:"invoke-ai-logo",sx:{opacity:.4,filter:"grayscale(1)",mt:-6,w:16,h:16,minW:16,minH:16,userSelect:"none"}})}),!n&&i.jsx(rj,{}),i.jsx(H,{sx:{position:"absolute",bottom:0,left:0,p:1,justifyContent:"center",alignItems:"center",w:"full",maxW:"full",borderBottomRadius:"base",bg:e?"accent.400":"base.500",color:e?"base.50":"base.100",_dark:{bg:e?"accent.500":"base.600",color:e?"base.50":"base.100"},lineHeight:"short",fontSize:"xs",fontWeight:e?700:500},children:r}),i.jsx(ly,{isSelected:e,isHovered:s}),i.jsx(iy,{data:p,dropLabel:i.jsx(tt,{fontSize:"md",children:"Move"})})]})})})})});aj.displayName="HoverableBoard";const nU=fe([Ye],({boards:e,gallery:t})=>{const{searchText:n}=e,{selectedBoardId:r}=t;return{selectedBoardId:r,searchText:n}},Ge),rU=e=>{const{isOpen:t}=e,{selectedBoardId:n,searchText:r}=z(nU),{data:o}=Zh(),s=r?o==null?void 0:o.filter(d=>d.board_name.toLowerCase().includes(r.toLowerCase())):o,[a,c]=f.useState();return i.jsxs(i.Fragment,{children:[i.jsx(sm,{in:t,animateOpacity:!0,children:i.jsxs(H,{layerStyle:"first",sx:{flexDir:"column",gap:2,p:2,mt:2,borderRadius:"base"},children:[i.jsxs(H,{sx:{gap:2,alignItems:"center"},children:[i.jsx(KV,{}),i.jsx(HV,{})]}),i.jsx(Q6,{defer:!0,style:{height:"100%",width:"100%"},options:{scrollbars:{visibility:"auto",autoHide:"move",autoHideDelay:1300,theme:"os-theme-dark"}},children:i.jsxs(rl,{className:"list-container",sx:{gridTemplateColumns:"repeat(auto-fill, minmax(108px, 1fr));",maxH:346},children:[i.jsx(Tv,{sx:{p:1.5},children:i.jsx(aj,{isSelected:n===void 0})}),s&&s.map(d=>i.jsx(Tv,{sx:{p:1.5},children:i.jsx(sj,{board:d,isSelected:n===d.board_id,setBoardToDelete:c})},d.board_id))]})})]})}),i.jsx(BV,{boardToDelete:a,setBoardToDelete:c})]})},oU=f.memo(rU),sU=fe([Ye],e=>{const{selectedBoardId:t}=e.gallery;return{selectedBoardId:t}},Ge),aU=e=>{const{isOpen:t,onToggle:n}=e,{selectedBoardId:r}=z(sU),o=Rm(r),s=f.useMemo(()=>o.length>20?`${o.substring(0,20)}...`:o,[o]);return i.jsxs(H,{as:gc,onClick:n,size:"sm",sx:{position:"relative",gap:2,w:"full",justifyContent:"space-between",alignItems:"center",px:2},children:[i.jsx(tt,{noOfLines:1,sx:{fontWeight:600,w:"100%",textAlign:"center",color:"base.800",_dark:{color:"base.200"}},children:s}),i.jsx(ay,{sx:{transform:t?"rotate(0deg)":"rotate(180deg)",transitionProperty:"common",transitionDuration:"normal"}})]})},iU=f.memo(aU);function ij(e){return rt({tag:"svg",attr:{fill:"currentColor",viewBox:"0 0 16 16"},child:[{tag:"path",attr:{d:"M9.828.722a.5.5 0 0 1 .354.146l4.95 4.95a.5.5 0 0 1 0 .707c-.48.48-1.072.588-1.503.588-.177 0-.335-.018-.46-.039l-3.134 3.134a5.927 5.927 0 0 1 .16 1.013c.046.702-.032 1.687-.72 2.375a.5.5 0 0 1-.707 0l-2.829-2.828-3.182 3.182c-.195.195-1.219.902-1.414.707-.195-.195.512-1.22.707-1.414l3.182-3.182-2.828-2.829a.5.5 0 0 1 0-.707c.688-.688 1.673-.767 2.375-.72a5.922 5.922 0 0 1 1.013.16l3.134-3.133a2.772 2.772 0 0 1-.04-.461c0-.43.108-1.022.589-1.503a.5.5 0 0 1 .353-.146z"}}]})(e)}function lj(e){return rt({tag:"svg",attr:{fill:"currentColor",viewBox:"0 0 16 16"},child:[{tag:"path",attr:{d:"M9.828.722a.5.5 0 0 1 .354.146l4.95 4.95a.5.5 0 0 1 0 .707c-.48.48-1.072.588-1.503.588-.177 0-.335-.018-.46-.039l-3.134 3.134a5.927 5.927 0 0 1 .16 1.013c.046.702-.032 1.687-.72 2.375a.5.5 0 0 1-.707 0l-2.829-2.828-3.182 3.182c-.195.195-1.219.902-1.414.707-.195-.195.512-1.22.707-1.414l3.182-3.182-2.828-2.829a.5.5 0 0 1 0-.707c.688-.688 1.673-.767 2.375-.72a5.922 5.922 0 0 1 1.013.16l3.134-3.133a2.772 2.772 0 0 1-.04-.461c0-.43.108-1.022.589-1.503a.5.5 0 0 1 .353-.146zm.122 2.112v-.002.002zm0-.002v.002a.5.5 0 0 1-.122.51L6.293 6.878a.5.5 0 0 1-.511.12H5.78l-.014-.004a4.507 4.507 0 0 0-.288-.076 4.922 4.922 0 0 0-.765-.116c-.422-.028-.836.008-1.175.15l5.51 5.509c.141-.34.177-.753.149-1.175a4.924 4.924 0 0 0-.192-1.054l-.004-.013v-.001a.5.5 0 0 1 .12-.512l3.536-3.535a.5.5 0 0 1 .532-.115l.096.022c.087.017.208.034.344.034.114 0 .23-.011.343-.04L9.927 2.028c-.029.113-.04.23-.04.343a1.779 1.779 0 0 0 .062.46z"}}]})(e)}const lU=fe([Ye],e=>{const{shouldPinGallery:t}=e.ui;return{shouldPinGallery:t}},Ge),cU=()=>{const e=te(),{t}=be(),{shouldPinGallery:n}=z(lU),r=()=>{e(D_()),e(So())};return i.jsx(Le,{size:"sm","aria-label":t("gallery.pinGallery"),tooltip:`${t("gallery.pinGallery")} (Shift+G)`,onClick:r,icon:n?i.jsx(ij,{}):i.jsx(lj,{})})},uU=e=>{const{triggerComponent:t,children:n,hasArrow:r=!0,isLazy:o=!0,...s}=e;return i.jsxs(Tb,{isLazy:o,...s,children:[i.jsx(Db,{children:t}),i.jsxs(Ab,{shadow:"dark-lg",children:[r&&i.jsx(y5,{}),n]})]})},gl=f.memo(uU),dU=e=>{const{label:t,...n}=e,{colorMode:r}=Ds();return i.jsx(H3,{colorScheme:"accent",...n,children:i.jsx(tt,{sx:{fontSize:"sm",color:ze("base.800","base.200")(r)},children:t})})},Gn=f.memo(dU);function fU(e){return rt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M12 16c1.671 0 3-1.331 3-3s-1.329-3-3-3-3 1.331-3 3 1.329 3 3 3z"}},{tag:"path",attr:{d:"M20.817 11.186a8.94 8.94 0 0 0-1.355-3.219 9.053 9.053 0 0 0-2.43-2.43 8.95 8.95 0 0 0-3.219-1.355 9.028 9.028 0 0 0-1.838-.18V2L8 5l3.975 3V6.002c.484-.002.968.044 1.435.14a6.961 6.961 0 0 1 2.502 1.053 7.005 7.005 0 0 1 1.892 1.892A6.967 6.967 0 0 1 19 13a7.032 7.032 0 0 1-.55 2.725 7.11 7.11 0 0 1-.644 1.188 7.2 7.2 0 0 1-.858 1.039 7.028 7.028 0 0 1-3.536 1.907 7.13 7.13 0 0 1-2.822 0 6.961 6.961 0 0 1-2.503-1.054 7.002 7.002 0 0 1-1.89-1.89A6.996 6.996 0 0 1 5 13H3a9.02 9.02 0 0 0 1.539 5.034 9.096 9.096 0 0 0 2.428 2.428A8.95 8.95 0 0 0 12 22a9.09 9.09 0 0 0 1.814-.183 9.014 9.014 0 0 0 3.218-1.355 8.886 8.886 0 0 0 1.331-1.099 9.228 9.228 0 0 0 1.1-1.332A8.952 8.952 0 0 0 21 13a9.09 9.09 0 0 0-.183-1.814z"}}]})(e)}const pU=e=>{const[t,n]=f.useState(!1),{label:r,value:o,min:s=1,max:a=100,step:c=1,onChange:d,tooltipSuffix:p="",withSliderMarks:h=!1,withInput:m=!1,isInteger:v=!1,inputWidth:b=16,withReset:w=!1,hideTooltip:y=!1,isCompact:S=!1,isDisabled:k=!1,sliderMarks:_,handleReset:I,sliderFormControlProps:P,sliderFormLabelProps:E,sliderMarkProps:O,sliderTrackProps:R,sliderThumbProps:M,sliderNumberInputProps:T,sliderNumberInputFieldProps:A,sliderNumberInputStepperProps:$,sliderTooltipProps:Q,sliderIAIIconButtonProps:B,...V}=e,q=te(),{t:G}=be(),[D,L]=f.useState(String(o));f.useEffect(()=>{L(o)},[o]);const W=f.useMemo(()=>T!=null&&T.min?T.min:s,[s,T==null?void 0:T.min]),Y=f.useMemo(()=>T!=null&&T.max?T.max:a,[a,T==null?void 0:T.max]),ae=f.useCallback(re=>{d(re)},[d]),ye=f.useCallback(re=>{re.target.value===""&&(re.target.value=String(W));const oe=Es(v?Math.floor(Number(re.target.value)):Number(D),W,Y),pe=wu(oe,c);d(pe),L(pe)},[v,D,W,Y,d,c]),ue=f.useCallback(re=>{L(re)},[]),X=f.useCallback(()=>{I&&I()},[I]),K=f.useCallback(re=>{re.target instanceof HTMLDivElement&&re.target.focus()},[]),U=f.useCallback(re=>{re.shiftKey&&q(_o(!0))},[q]),se=f.useCallback(re=>{re.shiftKey||q(_o(!1))},[q]);return i.jsxs(ho,{onClick:K,sx:S?{display:"flex",flexDirection:"row",alignItems:"center",columnGap:4,margin:0,padding:0}:{},isDisabled:k,...P,children:[r&&i.jsx(zo,{sx:m?{mb:-1.5}:{},...E,children:r}),i.jsxs(di,{w:"100%",gap:2,alignItems:"center",children:[i.jsxs($5,{"aria-label":r,value:o,min:s,max:a,step:c,onChange:ae,onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),focusThumbOnChange:!1,isDisabled:k,...V,children:[h&&!_&&i.jsxs(i.Fragment,{children:[i.jsx(Vl,{value:s,sx:{insetInlineStart:"0 !important",insetInlineEnd:"unset !important"},...O,children:s}),i.jsx(Vl,{value:a,sx:{insetInlineStart:"unset !important",insetInlineEnd:"0 !important"},...O,children:a})]}),h&&_&&i.jsx(i.Fragment,{children:_.map((re,oe)=>oe===0?i.jsx(Vl,{value:re,sx:{insetInlineStart:"0 !important",insetInlineEnd:"unset !important"},...O,children:re},re):oe===_.length-1?i.jsx(Vl,{value:re,sx:{insetInlineStart:"unset !important",insetInlineEnd:"0 !important"},...O,children:re},re):i.jsx(Vl,{value:re,sx:{transform:"translateX(-50%)"},...O,children:re},re))}),i.jsx(L5,{...R,children:i.jsx(B5,{})}),i.jsx(wn,{hasArrow:!0,placement:"top",isOpen:t,label:`${o}${p}`,hidden:y,...Q,children:i.jsx(z5,{...M,zIndex:0})})]}),m&&i.jsxs(dm,{min:W,max:Y,step:c,value:D,onChange:ue,onBlur:ye,focusInputOnChange:!1,...T,children:[i.jsx(pm,{onKeyDown:U,onKeyUp:se,minWidth:b,...A}),i.jsxs(fm,{...$,children:[i.jsx(mm,{onClick:()=>d(Number(D))}),i.jsx(hm,{onClick:()=>d(Number(D))})]})]}),w&&i.jsx(Le,{size:"sm","aria-label":G("accessibility.reset"),tooltip:G("accessibility.reset"),icon:i.jsx(fU,{}),isDisabled:k,onClick:X,...B})]})]})},_t=f.memo(pU);function hU(e){const t=f.createContext(null);return[({children:o,value:s})=>F.createElement(t.Provider,{value:s},o),()=>{const o=f.useContext(t);if(o===null)throw new Error(e);return o}]}function cj(e){return Array.isArray(e)?e:[e]}const mU=()=>{};function gU(e,t={active:!0}){return typeof e!="function"||!t.active?t.onKeyDown||mU:n=>{var r;n.key==="Escape"&&(e(n),(r=t.onTrigger)==null||r.call(t))}}function uj({data:e}){const t=[],n=[],r=e.reduce((o,s,a)=>(s.group?o[s.group]?o[s.group].push(a):o[s.group]=[a]:n.push(a),o),{});return Object.keys(r).forEach(o=>{t.push(...r[o].map(s=>e[s]))}),t.push(...n.map(o=>e[o])),t}function dj(e){return Array.isArray(e)||e===null?!1:typeof e=="object"?e.type!==F.Fragment:!1}function fj(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;tr===t[o]).indexOf(!1)>=0)&&(n.current={v:e(),prevDeps:[...t]}),n.current.v}const yU=$R({key:"mantine",prepend:!0});function xU(){return k3()||yU}var wU=Object.defineProperty,XS=Object.getOwnPropertySymbols,SU=Object.prototype.hasOwnProperty,CU=Object.prototype.propertyIsEnumerable,QS=(e,t,n)=>t in e?wU(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,kU=(e,t)=>{for(var n in t||(t={}))SU.call(t,n)&&QS(e,n,t[n]);if(XS)for(var n of XS(t))CU.call(t,n)&&QS(e,n,t[n]);return e};const W0="ref";function _U(e){let t;if(e.length!==1)return{args:e,ref:t};const[n]=e;if(!(n instanceof Object))return{args:e,ref:t};if(!(W0 in n))return{args:e,ref:t};t=n[W0];const r=kU({},n);return delete r[W0],{args:[r],ref:t}}const{cssFactory:PU}=(()=>{function e(n,r,o){const s=[],a=BR(n,s,o);return s.length<2?o:a+r(s)}function t(n){const{cache:r}=n,o=(...a)=>{const{ref:c,args:d}=_U(a),p=zR(d,r.registered);return LR(r,p,!1),`${r.key}-${p.name}${c===void 0?"":` ${c}`}`};return{css:o,cx:(...a)=>e(r.registered,o,pj(a))}}return{cssFactory:t}})();function hj(){const e=xU();return bU(()=>PU({cache:e}),[e])}function jU({cx:e,classes:t,context:n,classNames:r,name:o,cache:s}){const a=n.reduce((c,d)=>(Object.keys(d.classNames).forEach(p=>{typeof c[p]!="string"?c[p]=`${d.classNames[p]}`:c[p]=`${c[p]} ${d.classNames[p]}`}),c),{});return Object.keys(t).reduce((c,d)=>(c[d]=e(t[d],a[d],r!=null&&r[d],Array.isArray(o)?o.filter(Boolean).map(p=>`${(s==null?void 0:s.key)||"mantine"}-${p}-${d}`).join(" "):o?`${(s==null?void 0:s.key)||"mantine"}-${o}-${d}`:null),c),{})}var IU=Object.defineProperty,JS=Object.getOwnPropertySymbols,EU=Object.prototype.hasOwnProperty,OU=Object.prototype.propertyIsEnumerable,ZS=(e,t,n)=>t in e?IU(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,V0=(e,t)=>{for(var n in t||(t={}))EU.call(t,n)&&ZS(e,n,t[n]);if(JS)for(var n of JS(t))OU.call(t,n)&&ZS(e,n,t[n]);return e};function o1(e,t){return t&&Object.keys(t).forEach(n=>{e[n]?e[n]=V0(V0({},e[n]),t[n]):e[n]=V0({},t[n])}),e}function eC(e,t,n,r){const o=s=>typeof s=="function"?s(t,n||{},r):s||{};return Array.isArray(e)?e.map(s=>o(s.styles)).reduce((s,a)=>o1(s,a),{}):o(e)}function RU({ctx:e,theme:t,params:n,variant:r,size:o}){return e.reduce((s,a)=>(a.variants&&r in a.variants&&o1(s,a.variants[r](t,n,{variant:r,size:o})),a.sizes&&o in a.sizes&&o1(s,a.sizes[o](t,n,{variant:r,size:o})),s),{})}function so(e){const t=typeof e=="function"?e:()=>e;function n(r,o){const s=Fa(),a=$D(o==null?void 0:o.name),c=k3(),d={variant:o==null?void 0:o.variant,size:o==null?void 0:o.size},{css:p,cx:h}=hj(),m=t(s,r,d),v=eC(o==null?void 0:o.styles,s,r,d),b=eC(a,s,r,d),w=RU({ctx:a,theme:s,params:r,variant:o==null?void 0:o.variant,size:o==null?void 0:o.size}),y=Object.fromEntries(Object.keys(m).map(S=>{const k=h({[p(m[S])]:!(o!=null&&o.unstyled)},p(w[S]),p(b[S]),p(v[S]));return[S,k]}));return{classes:jU({cx:h,classes:y,context:a,classNames:o==null?void 0:o.classNames,name:o==null?void 0:o.name,cache:c}),cx:h,theme:s}}return n}function tC(e){return`___ref-${e||""}`}var MU=Object.defineProperty,DU=Object.defineProperties,TU=Object.getOwnPropertyDescriptors,nC=Object.getOwnPropertySymbols,AU=Object.prototype.hasOwnProperty,NU=Object.prototype.propertyIsEnumerable,rC=(e,t,n)=>t in e?MU(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,hu=(e,t)=>{for(var n in t||(t={}))AU.call(t,n)&&rC(e,n,t[n]);if(nC)for(var n of nC(t))NU.call(t,n)&&rC(e,n,t[n]);return e},mu=(e,t)=>DU(e,TU(t));const gu={in:{opacity:1,transform:"scale(1)"},out:{opacity:0,transform:`scale(.9) translateY(${Ue(10)})`},transitionProperty:"transform, opacity"},Jf={fade:{in:{opacity:1},out:{opacity:0},transitionProperty:"opacity"},scale:{in:{opacity:1,transform:"scale(1)"},out:{opacity:0,transform:"scale(0)"},common:{transformOrigin:"top"},transitionProperty:"transform, opacity"},"scale-y":{in:{opacity:1,transform:"scaleY(1)"},out:{opacity:0,transform:"scaleY(0)"},common:{transformOrigin:"top"},transitionProperty:"transform, opacity"},"scale-x":{in:{opacity:1,transform:"scaleX(1)"},out:{opacity:0,transform:"scaleX(0)"},common:{transformOrigin:"left"},transitionProperty:"transform, opacity"},"skew-up":{in:{opacity:1,transform:"translateY(0) skew(0deg, 0deg)"},out:{opacity:0,transform:`translateY(-${Ue(20)}) skew(-10deg, -5deg)`},common:{transformOrigin:"top"},transitionProperty:"transform, opacity"},"skew-down":{in:{opacity:1,transform:"translateY(0) skew(0deg, 0deg)"},out:{opacity:0,transform:`translateY(${Ue(20)}) skew(-10deg, -5deg)`},common:{transformOrigin:"bottom"},transitionProperty:"transform, opacity"},"rotate-left":{in:{opacity:1,transform:"translateY(0) rotate(0deg)"},out:{opacity:0,transform:`translateY(${Ue(20)}) rotate(-5deg)`},common:{transformOrigin:"bottom"},transitionProperty:"transform, opacity"},"rotate-right":{in:{opacity:1,transform:"translateY(0) rotate(0deg)"},out:{opacity:0,transform:`translateY(${Ue(20)}) rotate(5deg)`},common:{transformOrigin:"top"},transitionProperty:"transform, opacity"},"slide-down":{in:{opacity:1,transform:"translateY(0)"},out:{opacity:0,transform:"translateY(-100%)"},common:{transformOrigin:"top"},transitionProperty:"transform, opacity"},"slide-up":{in:{opacity:1,transform:"translateY(0)"},out:{opacity:0,transform:"translateY(100%)"},common:{transformOrigin:"bottom"},transitionProperty:"transform, opacity"},"slide-left":{in:{opacity:1,transform:"translateX(0)"},out:{opacity:0,transform:"translateX(100%)"},common:{transformOrigin:"left"},transitionProperty:"transform, opacity"},"slide-right":{in:{opacity:1,transform:"translateX(0)"},out:{opacity:0,transform:"translateX(-100%)"},common:{transformOrigin:"right"},transitionProperty:"transform, opacity"},pop:mu(hu({},gu),{common:{transformOrigin:"center center"}}),"pop-bottom-left":mu(hu({},gu),{common:{transformOrigin:"bottom left"}}),"pop-bottom-right":mu(hu({},gu),{common:{transformOrigin:"bottom right"}}),"pop-top-left":mu(hu({},gu),{common:{transformOrigin:"top left"}}),"pop-top-right":mu(hu({},gu),{common:{transformOrigin:"top right"}})},oC=["mousedown","touchstart"];function $U(e,t,n){const r=f.useRef();return f.useEffect(()=>{const o=s=>{const{target:a}=s??{};if(Array.isArray(n)){const c=(a==null?void 0:a.hasAttribute("data-ignore-outside-clicks"))||!document.body.contains(a)&&a.tagName!=="HTML";n.every(p=>!!p&&!s.composedPath().includes(p))&&!c&&e()}else r.current&&!r.current.contains(a)&&e()};return(t||oC).forEach(s=>document.addEventListener(s,o)),()=>{(t||oC).forEach(s=>document.removeEventListener(s,o))}},[r,e,n]),r}function zU(e,t){try{return e.addEventListener("change",t),()=>e.removeEventListener("change",t)}catch{return e.addListener(t),()=>e.removeListener(t)}}function LU(e,t){return typeof t=="boolean"?t:typeof window<"u"&&"matchMedia"in window?window.matchMedia(e).matches:!1}function BU(e,t,{getInitialValueInEffect:n}={getInitialValueInEffect:!0}){const[r,o]=f.useState(n?t:LU(e,t)),s=f.useRef();return f.useEffect(()=>{if("matchMedia"in window)return s.current=window.matchMedia(e),o(s.current.matches),zU(s.current,a=>o(a.matches))},[e]),r}const mj=typeof document<"u"?f.useLayoutEffect:f.useEffect;function Ps(e,t){const n=f.useRef(!1);f.useEffect(()=>()=>{n.current=!1},[]),f.useEffect(()=>{if(n.current)return e();n.current=!0},t)}function FU({opened:e,shouldReturnFocus:t=!0}){const n=f.useRef(),r=()=>{var o;n.current&&"focus"in n.current&&typeof n.current.focus=="function"&&((o=n.current)==null||o.focus({preventScroll:!0}))};return Ps(()=>{let o=-1;const s=a=>{a.key==="Tab"&&window.clearTimeout(o)};return document.addEventListener("keydown",s),e?n.current=document.activeElement:t&&(o=window.setTimeout(r,10)),()=>{window.clearTimeout(o),document.removeEventListener("keydown",s)}},[e,t]),r}const HU=/input|select|textarea|button|object/,gj="a, input, select, textarea, button, object, [tabindex]";function WU(e){return e.style.display==="none"}function VU(e){if(e.getAttribute("aria-hidden")||e.getAttribute("hidden")||e.getAttribute("type")==="hidden")return!1;let n=e;for(;n&&!(n===document.body||n.nodeType===11);){if(WU(n))return!1;n=n.parentNode}return!0}function vj(e){let t=e.getAttribute("tabindex");return t===null&&(t=void 0),parseInt(t,10)}function s1(e){const t=e.nodeName.toLowerCase(),n=!Number.isNaN(vj(e));return(HU.test(t)&&!e.disabled||e instanceof HTMLAnchorElement&&e.href||n)&&VU(e)}function bj(e){const t=vj(e);return(Number.isNaN(t)||t>=0)&&s1(e)}function UU(e){return Array.from(e.querySelectorAll(gj)).filter(bj)}function GU(e,t){const n=UU(e);if(!n.length){t.preventDefault();return}const r=n[t.shiftKey?0:n.length-1],o=e.getRootNode();if(!(r===o.activeElement||e===o.activeElement))return;t.preventDefault();const a=n[t.shiftKey?n.length-1:0];a&&a.focus()}function dy(){return`mantine-${Math.random().toString(36).slice(2,11)}`}function qU(e,t="body > :not(script)"){const n=dy(),r=Array.from(document.querySelectorAll(t)).map(o=>{var s;if((s=o==null?void 0:o.shadowRoot)!=null&&s.contains(e)||o.contains(e))return;const a=o.getAttribute("aria-hidden"),c=o.getAttribute("data-hidden"),d=o.getAttribute("data-focus-id");return o.setAttribute("data-focus-id",n),a===null||a==="false"?o.setAttribute("aria-hidden","true"):!c&&!d&&o.setAttribute("data-hidden",a),{node:o,ariaHidden:c||null}});return()=>{r.forEach(o=>{!o||n!==o.node.getAttribute("data-focus-id")||(o.ariaHidden===null?o.node.removeAttribute("aria-hidden"):o.node.setAttribute("aria-hidden",o.ariaHidden),o.node.removeAttribute("data-focus-id"),o.node.removeAttribute("data-hidden"))})}}function KU(e=!0){const t=f.useRef(),n=f.useRef(null),r=s=>{let a=s.querySelector("[data-autofocus]");if(!a){const c=Array.from(s.querySelectorAll(gj));a=c.find(bj)||c.find(s1)||null,!a&&s1(s)&&(a=s)}a&&a.focus({preventScroll:!0})},o=f.useCallback(s=>{if(e){if(s===null){n.current&&(n.current(),n.current=null);return}n.current=qU(s),t.current!==s&&(s?(setTimeout(()=>{s.getRootNode()&&r(s)}),t.current=s):t.current=null)}},[e]);return f.useEffect(()=>{if(!e)return;t.current&&setTimeout(()=>r(t.current));const s=a=>{a.key==="Tab"&&t.current&&GU(t.current,a)};return document.addEventListener("keydown",s),()=>{document.removeEventListener("keydown",s),n.current&&n.current()}},[e]),o}const YU=F["useId".toString()]||(()=>{});function XU(){const e=YU();return e?`mantine-${e.replace(/:/g,"")}`:""}function fy(e){const t=XU(),[n,r]=f.useState(t);return mj(()=>{r(dy())},[]),typeof e=="string"?e:typeof window>"u"?t:n}function sC(e,t,n){f.useEffect(()=>(window.addEventListener(e,t,n),()=>window.removeEventListener(e,t,n)),[e,t])}function yj(e,t){typeof e=="function"?e(t):typeof e=="object"&&e!==null&&"current"in e&&(e.current=t)}function QU(...e){return t=>{e.forEach(n=>yj(n,t))}}function Ad(...e){return f.useCallback(QU(...e),e)}function rd({value:e,defaultValue:t,finalValue:n,onChange:r=()=>{}}){const[o,s]=f.useState(t!==void 0?t:n),a=c=>{s(c),r==null||r(c)};return e!==void 0?[e,r,!0]:[o,a,!1]}function xj(e,t){return BU("(prefers-reduced-motion: reduce)",e,t)}const JU=e=>e<.5?2*e*e:-1+(4-2*e)*e,ZU=({axis:e,target:t,parent:n,alignment:r,offset:o,isList:s})=>{if(!t||!n&&typeof document>"u")return 0;const a=!!n,d=(n||document.body).getBoundingClientRect(),p=t.getBoundingClientRect(),h=m=>p[m]-d[m];if(e==="y"){const m=h("top");if(m===0)return 0;if(r==="start"){const b=m-o;return b<=p.height*(s?0:1)||!s?b:0}const v=a?d.height:window.innerHeight;if(r==="end"){const b=m+o-v+p.height;return b>=-p.height*(s?0:1)||!s?b:0}return r==="center"?m-v/2+p.height/2:0}if(e==="x"){const m=h("left");if(m===0)return 0;if(r==="start"){const b=m-o;return b<=p.width||!s?b:0}const v=a?d.width:window.innerWidth;if(r==="end"){const b=m+o-v+p.width;return b>=-p.width||!s?b:0}return r==="center"?m-v/2+p.width/2:0}return 0},eG=({axis:e,parent:t})=>{if(!t&&typeof document>"u")return 0;const n=e==="y"?"scrollTop":"scrollLeft";if(t)return t[n];const{body:r,documentElement:o}=document;return r[n]+o[n]},tG=({axis:e,parent:t,distance:n})=>{if(!t&&typeof document>"u")return;const r=e==="y"?"scrollTop":"scrollLeft";if(t)t[r]=n;else{const{body:o,documentElement:s}=document;o[r]=n,s[r]=n}};function wj({duration:e=1250,axis:t="y",onScrollFinish:n,easing:r=JU,offset:o=0,cancelable:s=!0,isList:a=!1}={}){const c=f.useRef(0),d=f.useRef(0),p=f.useRef(!1),h=f.useRef(null),m=f.useRef(null),v=xj(),b=()=>{c.current&&cancelAnimationFrame(c.current)},w=f.useCallback(({alignment:S="start"}={})=>{var k;p.current=!1,c.current&&b();const _=(k=eG({parent:h.current,axis:t}))!=null?k:0,I=ZU({parent:h.current,target:m.current,axis:t,alignment:S,offset:o,isList:a})-(h.current?0:_);function P(){d.current===0&&(d.current=performance.now());const O=performance.now()-d.current,R=v||e===0?1:O/e,M=_+I*r(R);tG({parent:h.current,axis:t,distance:M}),!p.current&&R<1?c.current=requestAnimationFrame(P):(typeof n=="function"&&n(),d.current=0,c.current=0,b())}P()},[t,e,r,a,o,n,v]),y=()=>{s&&(p.current=!0)};return sC("wheel",y,{passive:!0}),sC("touchmove",y,{passive:!0}),f.useEffect(()=>b,[]),{scrollableRef:h,targetRef:m,scrollIntoView:w,cancel:b}}var aC=Object.getOwnPropertySymbols,nG=Object.prototype.hasOwnProperty,rG=Object.prototype.propertyIsEnumerable,oG=(e,t)=>{var n={};for(var r in e)nG.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&aC)for(var r of aC(e))t.indexOf(r)<0&&rG.call(e,r)&&(n[r]=e[r]);return n};function Mm(e){const t=e,{m:n,mx:r,my:o,mt:s,mb:a,ml:c,mr:d,p,px:h,py:m,pt:v,pb:b,pl:w,pr:y,bg:S,c:k,opacity:_,ff:I,fz:P,fw:E,lts:O,ta:R,lh:M,fs:T,tt:A,td:$,w:Q,miw:B,maw:V,h:q,mih:G,mah:D,bgsz:L,bgp:W,bgr:Y,bga:ae,pos:ye,top:ue,left:X,bottom:K,right:U,inset:se,display:re}=t,oe=oG(t,["m","mx","my","mt","mb","ml","mr","p","px","py","pt","pb","pl","pr","bg","c","opacity","ff","fz","fw","lts","ta","lh","fs","tt","td","w","miw","maw","h","mih","mah","bgsz","bgp","bgr","bga","pos","top","left","bottom","right","inset","display"]);return{systemStyles:zD({m:n,mx:r,my:o,mt:s,mb:a,ml:c,mr:d,p,px:h,py:m,pt:v,pb:b,pl:w,pr:y,bg:S,c:k,opacity:_,ff:I,fz:P,fw:E,lts:O,ta:R,lh:M,fs:T,tt:A,td:$,w:Q,miw:B,maw:V,h:q,mih:G,mah:D,bgsz:L,bgp:W,bgr:Y,bga:ae,pos:ye,top:ue,left:X,bottom:K,right:U,inset:se,display:re}),rest:oe}}function sG(e,t){const n=Object.keys(e).filter(r=>r!=="base").sort((r,o)=>hw(Wt({size:r,sizes:t.breakpoints}))-hw(Wt({size:o,sizes:t.breakpoints})));return"base"in e?["base",...n]:n}function aG({value:e,theme:t,getValue:n,property:r}){if(e==null)return;if(typeof e=="object")return sG(e,t).reduce((a,c)=>{if(c==="base"&&e.base!==void 0){const p=n(e.base,t);return Array.isArray(r)?(r.forEach(h=>{a[h]=p}),a):(a[r]=p,a)}const d=n(e[c],t);return Array.isArray(r)?(a[t.fn.largerThan(c)]={},r.forEach(p=>{a[t.fn.largerThan(c)][p]=d}),a):(a[t.fn.largerThan(c)]={[r]:d},a)},{});const o=n(e,t);return Array.isArray(r)?r.reduce((s,a)=>(s[a]=o,s),{}):{[r]:o}}function iG(e,t){return e==="dimmed"?t.colorScheme==="dark"?t.colors.dark[2]:t.colors.gray[6]:t.fn.variant({variant:"filled",color:e,primaryFallback:!1}).background}function lG(e){return Ue(e)}function cG(e){return e}function uG(e,t){return Wt({size:e,sizes:t.fontSizes})}const dG=["-xs","-sm","-md","-lg","-xl"];function fG(e,t){return dG.includes(e)?`calc(${Wt({size:e.replace("-",""),sizes:t.spacing})} * -1)`:Wt({size:e,sizes:t.spacing})}const pG={identity:cG,color:iG,size:lG,fontSize:uG,spacing:fG},hG={m:{type:"spacing",property:"margin"},mt:{type:"spacing",property:"marginTop"},mb:{type:"spacing",property:"marginBottom"},ml:{type:"spacing",property:"marginLeft"},mr:{type:"spacing",property:"marginRight"},mx:{type:"spacing",property:["marginRight","marginLeft"]},my:{type:"spacing",property:["marginTop","marginBottom"]},p:{type:"spacing",property:"padding"},pt:{type:"spacing",property:"paddingTop"},pb:{type:"spacing",property:"paddingBottom"},pl:{type:"spacing",property:"paddingLeft"},pr:{type:"spacing",property:"paddingRight"},px:{type:"spacing",property:["paddingRight","paddingLeft"]},py:{type:"spacing",property:["paddingTop","paddingBottom"]},bg:{type:"color",property:"background"},c:{type:"color",property:"color"},opacity:{type:"identity",property:"opacity"},ff:{type:"identity",property:"fontFamily"},fz:{type:"fontSize",property:"fontSize"},fw:{type:"identity",property:"fontWeight"},lts:{type:"size",property:"letterSpacing"},ta:{type:"identity",property:"textAlign"},lh:{type:"identity",property:"lineHeight"},fs:{type:"identity",property:"fontStyle"},tt:{type:"identity",property:"textTransform"},td:{type:"identity",property:"textDecoration"},w:{type:"spacing",property:"width"},miw:{type:"spacing",property:"minWidth"},maw:{type:"spacing",property:"maxWidth"},h:{type:"spacing",property:"height"},mih:{type:"spacing",property:"minHeight"},mah:{type:"spacing",property:"maxHeight"},bgsz:{type:"size",property:"backgroundSize"},bgp:{type:"identity",property:"backgroundPosition"},bgr:{type:"identity",property:"backgroundRepeat"},bga:{type:"identity",property:"backgroundAttachment"},pos:{type:"identity",property:"position"},top:{type:"identity",property:"top"},left:{type:"size",property:"left"},bottom:{type:"size",property:"bottom"},right:{type:"size",property:"right"},inset:{type:"size",property:"inset"},display:{type:"identity",property:"display"}};var mG=Object.defineProperty,iC=Object.getOwnPropertySymbols,gG=Object.prototype.hasOwnProperty,vG=Object.prototype.propertyIsEnumerable,lC=(e,t,n)=>t in e?mG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,cC=(e,t)=>{for(var n in t||(t={}))gG.call(t,n)&&lC(e,n,t[n]);if(iC)for(var n of iC(t))vG.call(t,n)&&lC(e,n,t[n]);return e};function uC(e,t,n=hG){return Object.keys(n).reduce((o,s)=>(s in e&&e[s]!==void 0&&o.push(aG({value:e[s],getValue:pG[n[s].type],property:n[s].property,theme:t})),o),[]).reduce((o,s)=>(Object.keys(s).forEach(a=>{typeof s[a]=="object"&&s[a]!==null&&a in o?o[a]=cC(cC({},o[a]),s[a]):o[a]=s[a]}),o),{})}function dC(e,t){return typeof e=="function"?e(t):e}function bG(e,t,n){const r=Fa(),{css:o,cx:s}=hj();return Array.isArray(e)?s(n,o(uC(t,r)),e.map(a=>o(dC(a,r)))):s(n,o(dC(e,r)),o(uC(t,r)))}var yG=Object.defineProperty,rh=Object.getOwnPropertySymbols,Sj=Object.prototype.hasOwnProperty,Cj=Object.prototype.propertyIsEnumerable,fC=(e,t,n)=>t in e?yG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,xG=(e,t)=>{for(var n in t||(t={}))Sj.call(t,n)&&fC(e,n,t[n]);if(rh)for(var n of rh(t))Cj.call(t,n)&&fC(e,n,t[n]);return e},wG=(e,t)=>{var n={};for(var r in e)Sj.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&rh)for(var r of rh(e))t.indexOf(r)<0&&Cj.call(e,r)&&(n[r]=e[r]);return n};const kj=f.forwardRef((e,t)=>{var n=e,{className:r,component:o,style:s,sx:a}=n,c=wG(n,["className","component","style","sx"]);const{systemStyles:d,rest:p}=Mm(c),h=o||"div";return F.createElement(h,xG({ref:t,className:bG(a,d,r),style:s},p))});kj.displayName="@mantine/core/Box";const Po=kj;var SG=Object.defineProperty,CG=Object.defineProperties,kG=Object.getOwnPropertyDescriptors,pC=Object.getOwnPropertySymbols,_G=Object.prototype.hasOwnProperty,PG=Object.prototype.propertyIsEnumerable,hC=(e,t,n)=>t in e?SG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,mC=(e,t)=>{for(var n in t||(t={}))_G.call(t,n)&&hC(e,n,t[n]);if(pC)for(var n of pC(t))PG.call(t,n)&&hC(e,n,t[n]);return e},jG=(e,t)=>CG(e,kG(t)),IG=so(e=>({root:jG(mC(mC({},e.fn.focusStyles()),e.fn.fontStyles()),{cursor:"pointer",border:0,padding:0,appearance:"none",fontSize:e.fontSizes.md,backgroundColor:"transparent",textAlign:"left",color:e.colorScheme==="dark"?e.colors.dark[0]:e.black,textDecoration:"none",boxSizing:"border-box"})}));const EG=IG;var OG=Object.defineProperty,oh=Object.getOwnPropertySymbols,_j=Object.prototype.hasOwnProperty,Pj=Object.prototype.propertyIsEnumerable,gC=(e,t,n)=>t in e?OG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,RG=(e,t)=>{for(var n in t||(t={}))_j.call(t,n)&&gC(e,n,t[n]);if(oh)for(var n of oh(t))Pj.call(t,n)&&gC(e,n,t[n]);return e},MG=(e,t)=>{var n={};for(var r in e)_j.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&oh)for(var r of oh(e))t.indexOf(r)<0&&Pj.call(e,r)&&(n[r]=e[r]);return n};const jj=f.forwardRef((e,t)=>{const n=Sr("UnstyledButton",{},e),{className:r,component:o="button",unstyled:s,variant:a}=n,c=MG(n,["className","component","unstyled","variant"]),{classes:d,cx:p}=EG(null,{name:"UnstyledButton",unstyled:s,variant:a});return F.createElement(Po,RG({component:o,ref:t,className:p(d.root,r),type:o==="button"?"button":void 0},c))});jj.displayName="@mantine/core/UnstyledButton";const DG=jj;var TG=Object.defineProperty,AG=Object.defineProperties,NG=Object.getOwnPropertyDescriptors,vC=Object.getOwnPropertySymbols,$G=Object.prototype.hasOwnProperty,zG=Object.prototype.propertyIsEnumerable,bC=(e,t,n)=>t in e?TG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,a1=(e,t)=>{for(var n in t||(t={}))$G.call(t,n)&&bC(e,n,t[n]);if(vC)for(var n of vC(t))zG.call(t,n)&&bC(e,n,t[n]);return e},yC=(e,t)=>AG(e,NG(t));const LG=["subtle","filled","outline","light","default","transparent","gradient"],Zf={xs:Ue(18),sm:Ue(22),md:Ue(28),lg:Ue(34),xl:Ue(44)};function BG({variant:e,theme:t,color:n,gradient:r}){const o=t.fn.variant({color:n,variant:e,gradient:r});return e==="gradient"?{border:0,backgroundImage:o.background,color:o.color,"&:hover":t.fn.hover({backgroundSize:"200%"})}:LG.includes(e)?a1({border:`${Ue(1)} solid ${o.border}`,backgroundColor:o.background,color:o.color},t.fn.hover({backgroundColor:o.hover})):null}var FG=so((e,{radius:t,color:n,gradient:r},{variant:o,size:s})=>({root:yC(a1({position:"relative",borderRadius:e.fn.radius(t),padding:0,lineHeight:1,display:"flex",alignItems:"center",justifyContent:"center",height:Wt({size:s,sizes:Zf}),minHeight:Wt({size:s,sizes:Zf}),width:Wt({size:s,sizes:Zf}),minWidth:Wt({size:s,sizes:Zf})},BG({variant:o,theme:e,color:n,gradient:r})),{"&:active":e.activeStyles,"& [data-action-icon-loader]":{maxWidth:"70%"},"&:disabled, &[data-disabled]":{color:e.colors.gray[e.colorScheme==="dark"?6:4],cursor:"not-allowed",backgroundColor:o==="transparent"?void 0:e.fn.themeColor("gray",e.colorScheme==="dark"?8:1),borderColor:o==="transparent"?void 0:e.fn.themeColor("gray",e.colorScheme==="dark"?8:1),backgroundImage:"none",pointerEvents:"none","&:active":{transform:"none"}},"&[data-loading]":{pointerEvents:"none","&::before":yC(a1({content:'""'},e.fn.cover(Ue(-1))),{backgroundColor:e.colorScheme==="dark"?e.fn.rgba(e.colors.dark[7],.5):"rgba(255, 255, 255, .5)",borderRadius:e.fn.radius(t),cursor:"not-allowed"})}})}));const HG=FG;var WG=Object.defineProperty,sh=Object.getOwnPropertySymbols,Ij=Object.prototype.hasOwnProperty,Ej=Object.prototype.propertyIsEnumerable,xC=(e,t,n)=>t in e?WG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,wC=(e,t)=>{for(var n in t||(t={}))Ij.call(t,n)&&xC(e,n,t[n]);if(sh)for(var n of sh(t))Ej.call(t,n)&&xC(e,n,t[n]);return e},SC=(e,t)=>{var n={};for(var r in e)Ij.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&sh)for(var r of sh(e))t.indexOf(r)<0&&Ej.call(e,r)&&(n[r]=e[r]);return n};function VG(e){var t=e,{size:n,color:r}=t,o=SC(t,["size","color"]);const s=o,{style:a}=s,c=SC(s,["style"]);return F.createElement("svg",wC({viewBox:"0 0 135 140",xmlns:"http://www.w3.org/2000/svg",fill:r,style:wC({width:n},a)},c),F.createElement("rect",{y:"10",width:"15",height:"120",rx:"6"},F.createElement("animate",{attributeName:"height",begin:"0.5s",dur:"1s",values:"120;110;100;90;80;70;60;50;40;140;120",calcMode:"linear",repeatCount:"indefinite"}),F.createElement("animate",{attributeName:"y",begin:"0.5s",dur:"1s",values:"10;15;20;25;30;35;40;45;50;0;10",calcMode:"linear",repeatCount:"indefinite"})),F.createElement("rect",{x:"30",y:"10",width:"15",height:"120",rx:"6"},F.createElement("animate",{attributeName:"height",begin:"0.25s",dur:"1s",values:"120;110;100;90;80;70;60;50;40;140;120",calcMode:"linear",repeatCount:"indefinite"}),F.createElement("animate",{attributeName:"y",begin:"0.25s",dur:"1s",values:"10;15;20;25;30;35;40;45;50;0;10",calcMode:"linear",repeatCount:"indefinite"})),F.createElement("rect",{x:"60",width:"15",height:"140",rx:"6"},F.createElement("animate",{attributeName:"height",begin:"0s",dur:"1s",values:"120;110;100;90;80;70;60;50;40;140;120",calcMode:"linear",repeatCount:"indefinite"}),F.createElement("animate",{attributeName:"y",begin:"0s",dur:"1s",values:"10;15;20;25;30;35;40;45;50;0;10",calcMode:"linear",repeatCount:"indefinite"})),F.createElement("rect",{x:"90",y:"10",width:"15",height:"120",rx:"6"},F.createElement("animate",{attributeName:"height",begin:"0.25s",dur:"1s",values:"120;110;100;90;80;70;60;50;40;140;120",calcMode:"linear",repeatCount:"indefinite"}),F.createElement("animate",{attributeName:"y",begin:"0.25s",dur:"1s",values:"10;15;20;25;30;35;40;45;50;0;10",calcMode:"linear",repeatCount:"indefinite"})),F.createElement("rect",{x:"120",y:"10",width:"15",height:"120",rx:"6"},F.createElement("animate",{attributeName:"height",begin:"0.5s",dur:"1s",values:"120;110;100;90;80;70;60;50;40;140;120",calcMode:"linear",repeatCount:"indefinite"}),F.createElement("animate",{attributeName:"y",begin:"0.5s",dur:"1s",values:"10;15;20;25;30;35;40;45;50;0;10",calcMode:"linear",repeatCount:"indefinite"})))}var UG=Object.defineProperty,ah=Object.getOwnPropertySymbols,Oj=Object.prototype.hasOwnProperty,Rj=Object.prototype.propertyIsEnumerable,CC=(e,t,n)=>t in e?UG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,kC=(e,t)=>{for(var n in t||(t={}))Oj.call(t,n)&&CC(e,n,t[n]);if(ah)for(var n of ah(t))Rj.call(t,n)&&CC(e,n,t[n]);return e},_C=(e,t)=>{var n={};for(var r in e)Oj.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&ah)for(var r of ah(e))t.indexOf(r)<0&&Rj.call(e,r)&&(n[r]=e[r]);return n};function GG(e){var t=e,{size:n,color:r}=t,o=_C(t,["size","color"]);const s=o,{style:a}=s,c=_C(s,["style"]);return F.createElement("svg",kC({viewBox:"0 0 38 38",xmlns:"http://www.w3.org/2000/svg",stroke:r,style:kC({width:n,height:n},a)},c),F.createElement("g",{fill:"none",fillRule:"evenodd"},F.createElement("g",{transform:"translate(2.5 2.5)",strokeWidth:"5"},F.createElement("circle",{strokeOpacity:".5",cx:"16",cy:"16",r:"16"}),F.createElement("path",{d:"M32 16c0-9.94-8.06-16-16-16"},F.createElement("animateTransform",{attributeName:"transform",type:"rotate",from:"0 16 16",to:"360 16 16",dur:"1s",repeatCount:"indefinite"})))))}var qG=Object.defineProperty,ih=Object.getOwnPropertySymbols,Mj=Object.prototype.hasOwnProperty,Dj=Object.prototype.propertyIsEnumerable,PC=(e,t,n)=>t in e?qG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,jC=(e,t)=>{for(var n in t||(t={}))Mj.call(t,n)&&PC(e,n,t[n]);if(ih)for(var n of ih(t))Dj.call(t,n)&&PC(e,n,t[n]);return e},IC=(e,t)=>{var n={};for(var r in e)Mj.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&ih)for(var r of ih(e))t.indexOf(r)<0&&Dj.call(e,r)&&(n[r]=e[r]);return n};function KG(e){var t=e,{size:n,color:r}=t,o=IC(t,["size","color"]);const s=o,{style:a}=s,c=IC(s,["style"]);return F.createElement("svg",jC({viewBox:"0 0 120 30",xmlns:"http://www.w3.org/2000/svg",fill:r,style:jC({width:n},a)},c),F.createElement("circle",{cx:"15",cy:"15",r:"15"},F.createElement("animate",{attributeName:"r",from:"15",to:"15",begin:"0s",dur:"0.8s",values:"15;9;15",calcMode:"linear",repeatCount:"indefinite"}),F.createElement("animate",{attributeName:"fill-opacity",from:"1",to:"1",begin:"0s",dur:"0.8s",values:"1;.5;1",calcMode:"linear",repeatCount:"indefinite"})),F.createElement("circle",{cx:"60",cy:"15",r:"9",fillOpacity:"0.3"},F.createElement("animate",{attributeName:"r",from:"9",to:"9",begin:"0s",dur:"0.8s",values:"9;15;9",calcMode:"linear",repeatCount:"indefinite"}),F.createElement("animate",{attributeName:"fill-opacity",from:"0.5",to:"0.5",begin:"0s",dur:"0.8s",values:".5;1;.5",calcMode:"linear",repeatCount:"indefinite"})),F.createElement("circle",{cx:"105",cy:"15",r:"15"},F.createElement("animate",{attributeName:"r",from:"15",to:"15",begin:"0s",dur:"0.8s",values:"15;9;15",calcMode:"linear",repeatCount:"indefinite"}),F.createElement("animate",{attributeName:"fill-opacity",from:"1",to:"1",begin:"0s",dur:"0.8s",values:"1;.5;1",calcMode:"linear",repeatCount:"indefinite"})))}var YG=Object.defineProperty,lh=Object.getOwnPropertySymbols,Tj=Object.prototype.hasOwnProperty,Aj=Object.prototype.propertyIsEnumerable,EC=(e,t,n)=>t in e?YG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,XG=(e,t)=>{for(var n in t||(t={}))Tj.call(t,n)&&EC(e,n,t[n]);if(lh)for(var n of lh(t))Aj.call(t,n)&&EC(e,n,t[n]);return e},QG=(e,t)=>{var n={};for(var r in e)Tj.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&lh)for(var r of lh(e))t.indexOf(r)<0&&Aj.call(e,r)&&(n[r]=e[r]);return n};const U0={bars:VG,oval:GG,dots:KG},JG={xs:Ue(18),sm:Ue(22),md:Ue(36),lg:Ue(44),xl:Ue(58)},ZG={size:"md"};function Nj(e){const t=Sr("Loader",ZG,e),{size:n,color:r,variant:o}=t,s=QG(t,["size","color","variant"]),a=Fa(),c=o in U0?o:a.loader;return F.createElement(Po,XG({role:"presentation",component:U0[c]||U0.bars,size:Wt({size:n,sizes:JG}),color:a.fn.variant({variant:"filled",primaryFallback:!1,color:r||a.primaryColor}).background},s))}Nj.displayName="@mantine/core/Loader";var eq=Object.defineProperty,ch=Object.getOwnPropertySymbols,$j=Object.prototype.hasOwnProperty,zj=Object.prototype.propertyIsEnumerable,OC=(e,t,n)=>t in e?eq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,RC=(e,t)=>{for(var n in t||(t={}))$j.call(t,n)&&OC(e,n,t[n]);if(ch)for(var n of ch(t))zj.call(t,n)&&OC(e,n,t[n]);return e},tq=(e,t)=>{var n={};for(var r in e)$j.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&ch)for(var r of ch(e))t.indexOf(r)<0&&zj.call(e,r)&&(n[r]=e[r]);return n};const nq={color:"gray",size:"md",variant:"subtle"},Lj=f.forwardRef((e,t)=>{const n=Sr("ActionIcon",nq,e),{className:r,color:o,children:s,radius:a,size:c,variant:d,gradient:p,disabled:h,loaderProps:m,loading:v,unstyled:b,__staticSelector:w}=n,y=tq(n,["className","color","children","radius","size","variant","gradient","disabled","loaderProps","loading","unstyled","__staticSelector"]),{classes:S,cx:k,theme:_}=HG({radius:a,color:o,gradient:p},{name:["ActionIcon",w],unstyled:b,size:c,variant:d}),I=F.createElement(Nj,RC({color:_.fn.variant({color:o,variant:d}).color,size:"100%","data-action-icon-loader":!0},m));return F.createElement(DG,RC({className:k(S.root,r),ref:t,disabled:h,"data-disabled":h||void 0,"data-loading":v||void 0,unstyled:b},y),v?I:s)});Lj.displayName="@mantine/core/ActionIcon";const rq=Lj;var oq=Object.defineProperty,sq=Object.defineProperties,aq=Object.getOwnPropertyDescriptors,uh=Object.getOwnPropertySymbols,Bj=Object.prototype.hasOwnProperty,Fj=Object.prototype.propertyIsEnumerable,MC=(e,t,n)=>t in e?oq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,iq=(e,t)=>{for(var n in t||(t={}))Bj.call(t,n)&&MC(e,n,t[n]);if(uh)for(var n of uh(t))Fj.call(t,n)&&MC(e,n,t[n]);return e},lq=(e,t)=>sq(e,aq(t)),cq=(e,t)=>{var n={};for(var r in e)Bj.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&uh)for(var r of uh(e))t.indexOf(r)<0&&Fj.call(e,r)&&(n[r]=e[r]);return n};function Hj(e){const t=Sr("Portal",{},e),{children:n,target:r,className:o,innerRef:s}=t,a=cq(t,["children","target","className","innerRef"]),c=Fa(),[d,p]=f.useState(!1),h=f.useRef();return mj(()=>(p(!0),h.current=r?typeof r=="string"?document.querySelector(r):r:document.createElement("div"),r||document.body.appendChild(h.current),()=>{!r&&document.body.removeChild(h.current)}),[r]),d?_i.createPortal(F.createElement("div",lq(iq({className:o,dir:c.dir},a),{ref:s}),n),h.current):null}Hj.displayName="@mantine/core/Portal";var uq=Object.defineProperty,dh=Object.getOwnPropertySymbols,Wj=Object.prototype.hasOwnProperty,Vj=Object.prototype.propertyIsEnumerable,DC=(e,t,n)=>t in e?uq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,dq=(e,t)=>{for(var n in t||(t={}))Wj.call(t,n)&&DC(e,n,t[n]);if(dh)for(var n of dh(t))Vj.call(t,n)&&DC(e,n,t[n]);return e},fq=(e,t)=>{var n={};for(var r in e)Wj.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&dh)for(var r of dh(e))t.indexOf(r)<0&&Vj.call(e,r)&&(n[r]=e[r]);return n};function Uj(e){var t=e,{withinPortal:n=!0,children:r}=t,o=fq(t,["withinPortal","children"]);return n?F.createElement(Hj,dq({},o),r):F.createElement(F.Fragment,null,r)}Uj.displayName="@mantine/core/OptionalPortal";var pq=Object.defineProperty,fh=Object.getOwnPropertySymbols,Gj=Object.prototype.hasOwnProperty,qj=Object.prototype.propertyIsEnumerable,TC=(e,t,n)=>t in e?pq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,AC=(e,t)=>{for(var n in t||(t={}))Gj.call(t,n)&&TC(e,n,t[n]);if(fh)for(var n of fh(t))qj.call(t,n)&&TC(e,n,t[n]);return e},hq=(e,t)=>{var n={};for(var r in e)Gj.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&fh)for(var r of fh(e))t.indexOf(r)<0&&qj.call(e,r)&&(n[r]=e[r]);return n};function Kj(e){const t=e,{width:n,height:r,style:o}=t,s=hq(t,["width","height","style"]);return F.createElement("svg",AC({viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:AC({width:n,height:r},o)},s),F.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:"currentColor",fillRule:"evenodd",clipRule:"evenodd"}))}Kj.displayName="@mantine/core/CloseIcon";var mq=Object.defineProperty,ph=Object.getOwnPropertySymbols,Yj=Object.prototype.hasOwnProperty,Xj=Object.prototype.propertyIsEnumerable,NC=(e,t,n)=>t in e?mq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,gq=(e,t)=>{for(var n in t||(t={}))Yj.call(t,n)&&NC(e,n,t[n]);if(ph)for(var n of ph(t))Xj.call(t,n)&&NC(e,n,t[n]);return e},vq=(e,t)=>{var n={};for(var r in e)Yj.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&ph)for(var r of ph(e))t.indexOf(r)<0&&Xj.call(e,r)&&(n[r]=e[r]);return n};const bq={xs:Ue(12),sm:Ue(16),md:Ue(20),lg:Ue(28),xl:Ue(34)},yq={size:"sm"},Qj=f.forwardRef((e,t)=>{const n=Sr("CloseButton",yq,e),{iconSize:r,size:o,children:s}=n,a=vq(n,["iconSize","size","children"]),c=Ue(r||bq[o]);return F.createElement(rq,gq({ref:t,__staticSelector:"CloseButton",size:o},a),s||F.createElement(Kj,{width:c,height:c}))});Qj.displayName="@mantine/core/CloseButton";const Jj=Qj;var xq=Object.defineProperty,wq=Object.defineProperties,Sq=Object.getOwnPropertyDescriptors,$C=Object.getOwnPropertySymbols,Cq=Object.prototype.hasOwnProperty,kq=Object.prototype.propertyIsEnumerable,zC=(e,t,n)=>t in e?xq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ep=(e,t)=>{for(var n in t||(t={}))Cq.call(t,n)&&zC(e,n,t[n]);if($C)for(var n of $C(t))kq.call(t,n)&&zC(e,n,t[n]);return e},_q=(e,t)=>wq(e,Sq(t));function Pq({underline:e,strikethrough:t}){const n=[];return e&&n.push("underline"),t&&n.push("line-through"),n.length>0?n.join(" "):"none"}function jq({theme:e,color:t}){return t==="dimmed"?e.fn.dimmed():typeof t=="string"&&(t in e.colors||t.split(".")[0]in e.colors)?e.fn.variant({variant:"filled",color:t}).background:t||"inherit"}function Iq(e){return typeof e=="number"?{overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:e,WebkitBoxOrient:"vertical"}:null}function Eq({theme:e,truncate:t}){return t==="start"?{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:e.dir==="ltr"?"rtl":"ltr",textAlign:e.dir==="ltr"?"right":"left"}:t?{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}:null}var Oq=so((e,{color:t,lineClamp:n,truncate:r,inline:o,inherit:s,underline:a,gradient:c,weight:d,transform:p,align:h,strikethrough:m,italic:v},{size:b})=>{const w=e.fn.variant({variant:"gradient",gradient:c});return{root:_q(ep(ep(ep(ep({},e.fn.fontStyles()),e.fn.focusStyles()),Iq(n)),Eq({theme:e,truncate:r})),{color:jq({color:t,theme:e}),fontFamily:s?"inherit":e.fontFamily,fontSize:s||b===void 0?"inherit":Wt({size:b,sizes:e.fontSizes}),lineHeight:s?"inherit":o?1:e.lineHeight,textDecoration:Pq({underline:a,strikethrough:m}),WebkitTapHighlightColor:"transparent",fontWeight:s?"inherit":d,textTransform:p,textAlign:h,fontStyle:v?"italic":void 0}),gradient:{backgroundImage:w.background,WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent"}}});const Rq=Oq;var Mq=Object.defineProperty,hh=Object.getOwnPropertySymbols,Zj=Object.prototype.hasOwnProperty,eI=Object.prototype.propertyIsEnumerable,LC=(e,t,n)=>t in e?Mq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Dq=(e,t)=>{for(var n in t||(t={}))Zj.call(t,n)&&LC(e,n,t[n]);if(hh)for(var n of hh(t))eI.call(t,n)&&LC(e,n,t[n]);return e},Tq=(e,t)=>{var n={};for(var r in e)Zj.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&hh)for(var r of hh(e))t.indexOf(r)<0&&eI.call(e,r)&&(n[r]=e[r]);return n};const Aq={variant:"text"},tI=f.forwardRef((e,t)=>{const n=Sr("Text",Aq,e),{className:r,size:o,weight:s,transform:a,color:c,align:d,variant:p,lineClamp:h,truncate:m,gradient:v,inline:b,inherit:w,underline:y,strikethrough:S,italic:k,classNames:_,styles:I,unstyled:P,span:E,__staticSelector:O}=n,R=Tq(n,["className","size","weight","transform","color","align","variant","lineClamp","truncate","gradient","inline","inherit","underline","strikethrough","italic","classNames","styles","unstyled","span","__staticSelector"]),{classes:M,cx:T}=Rq({color:c,lineClamp:h,truncate:m,inline:b,inherit:w,underline:y,strikethrough:S,italic:k,weight:s,transform:a,align:d,gradient:v},{unstyled:P,name:O||"Text",variant:p,size:o});return F.createElement(Po,Dq({ref:t,className:T(M.root,{[M.gradient]:p==="gradient"},r),component:E?"span":"div"},R))});tI.displayName="@mantine/core/Text";const Sc=tI,tp={xs:Ue(1),sm:Ue(2),md:Ue(3),lg:Ue(4),xl:Ue(5)};function np(e,t){const n=e.fn.variant({variant:"outline",color:t}).border;return typeof t=="string"&&(t in e.colors||t.split(".")[0]in e.colors)?n:t===void 0?e.colorScheme==="dark"?e.colors.dark[4]:e.colors.gray[4]:t}var Nq=so((e,{color:t},{size:n,variant:r})=>({root:{},withLabel:{borderTop:"0 !important"},left:{"&::before":{display:"none"}},right:{"&::after":{display:"none"}},label:{display:"flex",alignItems:"center","&::before":{content:'""',flex:1,height:Ue(1),borderTop:`${Wt({size:n,sizes:tp})} ${r} ${np(e,t)}`,marginRight:e.spacing.xs},"&::after":{content:'""',flex:1,borderTop:`${Wt({size:n,sizes:tp})} ${r} ${np(e,t)}`,marginLeft:e.spacing.xs}},labelDefaultStyles:{color:t==="dark"?e.colors.dark[1]:e.fn.themeColor(t,e.colorScheme==="dark"?5:e.fn.primaryShade(),!1)},horizontal:{border:0,borderTopWidth:Ue(Wt({size:n,sizes:tp})),borderTopColor:np(e,t),borderTopStyle:r,margin:0},vertical:{border:0,alignSelf:"stretch",height:"auto",borderLeftWidth:Ue(Wt({size:n,sizes:tp})),borderLeftColor:np(e,t),borderLeftStyle:r}}));const $q=Nq;var zq=Object.defineProperty,Lq=Object.defineProperties,Bq=Object.getOwnPropertyDescriptors,mh=Object.getOwnPropertySymbols,nI=Object.prototype.hasOwnProperty,rI=Object.prototype.propertyIsEnumerable,BC=(e,t,n)=>t in e?zq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,FC=(e,t)=>{for(var n in t||(t={}))nI.call(t,n)&&BC(e,n,t[n]);if(mh)for(var n of mh(t))rI.call(t,n)&&BC(e,n,t[n]);return e},Fq=(e,t)=>Lq(e,Bq(t)),Hq=(e,t)=>{var n={};for(var r in e)nI.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&mh)for(var r of mh(e))t.indexOf(r)<0&&rI.call(e,r)&&(n[r]=e[r]);return n};const Wq={orientation:"horizontal",size:"xs",labelPosition:"left",variant:"solid"},i1=f.forwardRef((e,t)=>{const n=Sr("Divider",Wq,e),{className:r,color:o,orientation:s,size:a,label:c,labelPosition:d,labelProps:p,variant:h,styles:m,classNames:v,unstyled:b}=n,w=Hq(n,["className","color","orientation","size","label","labelPosition","labelProps","variant","styles","classNames","unstyled"]),{classes:y,cx:S}=$q({color:o},{classNames:v,styles:m,unstyled:b,name:"Divider",variant:h,size:a}),k=s==="vertical",_=s==="horizontal",I=!!c&&_,P=!(p!=null&&p.color);return F.createElement(Po,FC({ref:t,className:S(y.root,{[y.vertical]:k,[y.horizontal]:_,[y.withLabel]:I},r),role:"separator"},w),I&&F.createElement(Sc,Fq(FC({},p),{size:(p==null?void 0:p.size)||"xs",mt:Ue(2),className:S(y.label,y[d],{[y.labelDefaultStyles]:P})}),c))});i1.displayName="@mantine/core/Divider";var Vq=Object.defineProperty,Uq=Object.defineProperties,Gq=Object.getOwnPropertyDescriptors,HC=Object.getOwnPropertySymbols,qq=Object.prototype.hasOwnProperty,Kq=Object.prototype.propertyIsEnumerable,WC=(e,t,n)=>t in e?Vq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,VC=(e,t)=>{for(var n in t||(t={}))qq.call(t,n)&&WC(e,n,t[n]);if(HC)for(var n of HC(t))Kq.call(t,n)&&WC(e,n,t[n]);return e},Yq=(e,t)=>Uq(e,Gq(t)),Xq=so((e,t,{size:n})=>({item:Yq(VC({},e.fn.fontStyles()),{boxSizing:"border-box",wordBreak:"break-all",textAlign:"left",width:"100%",padding:`calc(${Wt({size:n,sizes:e.spacing})} / 1.5) ${Wt({size:n,sizes:e.spacing})}`,cursor:"pointer",fontSize:Wt({size:n,sizes:e.fontSizes}),color:e.colorScheme==="dark"?e.colors.dark[0]:e.black,borderRadius:e.fn.radius(),"&[data-hovered]":{backgroundColor:e.colorScheme==="dark"?e.colors.dark[4]:e.colors.gray[1]},"&[data-selected]":VC({backgroundColor:e.fn.variant({variant:"filled"}).background,color:e.fn.variant({variant:"filled"}).color},e.fn.hover({backgroundColor:e.fn.variant({variant:"filled"}).hover})),"&[data-disabled]":{cursor:"default",color:e.colors.dark[2]}}),nothingFound:{boxSizing:"border-box",color:e.colors.gray[6],paddingTop:`calc(${Wt({size:n,sizes:e.spacing})} / 2)`,paddingBottom:`calc(${Wt({size:n,sizes:e.spacing})} / 2)`,textAlign:"center"},separator:{boxSizing:"border-box",textAlign:"left",width:"100%",padding:`calc(${Wt({size:n,sizes:e.spacing})} / 1.5) ${Wt({size:n,sizes:e.spacing})}`},separatorLabel:{color:e.colorScheme==="dark"?e.colors.dark[3]:e.colors.gray[5]}}));const Qq=Xq;var Jq=Object.defineProperty,UC=Object.getOwnPropertySymbols,Zq=Object.prototype.hasOwnProperty,eK=Object.prototype.propertyIsEnumerable,GC=(e,t,n)=>t in e?Jq(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,tK=(e,t)=>{for(var n in t||(t={}))Zq.call(t,n)&&GC(e,n,t[n]);if(UC)for(var n of UC(t))eK.call(t,n)&&GC(e,n,t[n]);return e};function py({data:e,hovered:t,classNames:n,styles:r,isItemSelected:o,uuid:s,__staticSelector:a,onItemHover:c,onItemSelect:d,itemsRefs:p,itemComponent:h,size:m,nothingFound:v,creatable:b,createLabel:w,unstyled:y,variant:S}){const{classes:k}=Qq(null,{classNames:n,styles:r,unstyled:y,name:a,variant:S,size:m}),_=[],I=[];let P=null;const E=(R,M)=>{const T=typeof o=="function"?o(R.value):!1;return F.createElement(h,tK({key:R.value,className:k.item,"data-disabled":R.disabled||void 0,"data-hovered":!R.disabled&&t===M||void 0,"data-selected":!R.disabled&&T||void 0,selected:T,onMouseEnter:()=>c(M),id:`${s}-${M}`,role:"option",tabIndex:-1,"aria-selected":t===M,ref:A=>{p&&p.current&&(p.current[R.value]=A)},onMouseDown:R.disabled?null:A=>{A.preventDefault(),d(R)},disabled:R.disabled,variant:S},R))};let O=null;if(e.forEach((R,M)=>{R.creatable?P=M:R.group?(O!==R.group&&(O=R.group,I.push(F.createElement("div",{className:k.separator,key:`__mantine-divider-${M}`},F.createElement(i1,{classNames:{label:k.separatorLabel},label:R.group})))),I.push(E(R,M))):_.push(E(R,M))}),b){const R=e[P];_.push(F.createElement("div",{key:dy(),className:k.item,"data-hovered":t===P||void 0,onMouseEnter:()=>c(P),onMouseDown:M=>{M.preventDefault(),d(R)},tabIndex:-1,ref:M=>{p&&p.current&&(p.current[R.value]=M)}},w))}return I.length>0&&_.length>0&&_.unshift(F.createElement("div",{className:k.separator,key:"empty-group-separator"},F.createElement(i1,null))),I.length>0||_.length>0?F.createElement(F.Fragment,null,I,_):F.createElement(Sc,{size:m,unstyled:y,className:k.nothingFound},v)}py.displayName="@mantine/core/SelectItems";var nK=Object.defineProperty,gh=Object.getOwnPropertySymbols,oI=Object.prototype.hasOwnProperty,sI=Object.prototype.propertyIsEnumerable,qC=(e,t,n)=>t in e?nK(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,rK=(e,t)=>{for(var n in t||(t={}))oI.call(t,n)&&qC(e,n,t[n]);if(gh)for(var n of gh(t))sI.call(t,n)&&qC(e,n,t[n]);return e},oK=(e,t)=>{var n={};for(var r in e)oI.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&gh)for(var r of gh(e))t.indexOf(r)<0&&sI.call(e,r)&&(n[r]=e[r]);return n};const hy=f.forwardRef((e,t)=>{var n=e,{label:r,value:o}=n,s=oK(n,["label","value"]);return F.createElement("div",rK({ref:t},s),r||o)});hy.displayName="@mantine/core/DefaultItem";function sK(e,t){typeof e=="function"?e(t):e!=null&&(e.current=t)}function aI(...e){return t=>e.forEach(n=>sK(n,t))}function vl(...e){return f.useCallback(aI(...e),e)}const iI=f.forwardRef((e,t)=>{const{children:n,...r}=e,o=f.Children.toArray(n),s=o.find(iK);if(s){const a=s.props.children,c=o.map(d=>d===s?f.Children.count(a)>1?f.Children.only(null):f.isValidElement(a)?a.props.children:null:d);return f.createElement(l1,or({},r,{ref:t}),f.isValidElement(a)?f.cloneElement(a,void 0,c):null)}return f.createElement(l1,or({},r,{ref:t}),n)});iI.displayName="Slot";const l1=f.forwardRef((e,t)=>{const{children:n,...r}=e;return f.isValidElement(n)?f.cloneElement(n,{...lK(r,n.props),ref:aI(t,n.ref)}):f.Children.count(n)>1?f.Children.only(null):null});l1.displayName="SlotClone";const aK=({children:e})=>f.createElement(f.Fragment,null,e);function iK(e){return f.isValidElement(e)&&e.type===aK}function lK(e,t){const n={...t};for(const r in t){const o=e[r],s=t[r];/^on[A-Z]/.test(r)?o&&s?n[r]=(...c)=>{s(...c),o(...c)}:o&&(n[r]=o):r==="style"?n[r]={...o,...s}:r==="className"&&(n[r]=[o,s].filter(Boolean).join(" "))}return{...e,...n}}const cK=["a","button","div","h2","h3","img","label","li","nav","ol","p","span","svg","ul"],Nd=cK.reduce((e,t)=>{const n=f.forwardRef((r,o)=>{const{asChild:s,...a}=r,c=s?iI:t;return f.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),f.createElement(c,or({},a,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{}),c1=globalThis!=null&&globalThis.document?f.useLayoutEffect:()=>{};function uK(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const $d=e=>{const{present:t,children:n}=e,r=dK(t),o=typeof n=="function"?n({present:r.isPresent}):f.Children.only(n),s=vl(r.ref,o.ref);return typeof n=="function"||r.isPresent?f.cloneElement(o,{ref:s}):null};$d.displayName="Presence";function dK(e){const[t,n]=f.useState(),r=f.useRef({}),o=f.useRef(e),s=f.useRef("none"),a=e?"mounted":"unmounted",[c,d]=uK(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return f.useEffect(()=>{const p=rp(r.current);s.current=c==="mounted"?p:"none"},[c]),c1(()=>{const p=r.current,h=o.current;if(h!==e){const v=s.current,b=rp(p);e?d("MOUNT"):b==="none"||(p==null?void 0:p.display)==="none"?d("UNMOUNT"):d(h&&v!==b?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,d]),c1(()=>{if(t){const p=m=>{const b=rp(r.current).includes(m.animationName);m.target===t&&b&&_i.flushSync(()=>d("ANIMATION_END"))},h=m=>{m.target===t&&(s.current=rp(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",p),t.addEventListener("animationend",p),()=>{t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",p),t.removeEventListener("animationend",p)}}else d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:f.useCallback(p=>{p&&(r.current=getComputedStyle(p)),n(p)},[])}}function rp(e){return(e==null?void 0:e.animationName)||"none"}function fK(e,t=[]){let n=[];function r(s,a){const c=f.createContext(a),d=n.length;n=[...n,a];function p(m){const{scope:v,children:b,...w}=m,y=(v==null?void 0:v[e][d])||c,S=f.useMemo(()=>w,Object.values(w));return f.createElement(y.Provider,{value:S},b)}function h(m,v){const b=(v==null?void 0:v[e][d])||c,w=f.useContext(b);if(w)return w;if(a!==void 0)return a;throw new Error(`\`${m}\` must be used within \`${s}\``)}return p.displayName=s+"Provider",[p,h]}const o=()=>{const s=n.map(a=>f.createContext(a));return function(c){const d=(c==null?void 0:c[e])||s;return f.useMemo(()=>({[`__scope${e}`]:{...c,[e]:d}}),[c,d])}};return o.scopeName=e,[r,pK(o,...t)]}function pK(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const a=r.reduce((c,{useScope:d,scopeName:p})=>{const m=d(s)[`__scope${p}`];return{...c,...m}},{});return f.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}function Ui(e){const t=f.useRef(e);return f.useEffect(()=>{t.current=e}),f.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}const hK=f.createContext(void 0);function mK(e){const t=f.useContext(hK);return e||t||"ltr"}function gK(e,[t,n]){return Math.min(n,Math.max(t,e))}function Zi(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function vK(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const lI="ScrollArea",[cI,mde]=fK(lI),[bK,ds]=cI(lI),yK=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:s=600,...a}=e,[c,d]=f.useState(null),[p,h]=f.useState(null),[m,v]=f.useState(null),[b,w]=f.useState(null),[y,S]=f.useState(null),[k,_]=f.useState(0),[I,P]=f.useState(0),[E,O]=f.useState(!1),[R,M]=f.useState(!1),T=vl(t,$=>d($)),A=mK(o);return f.createElement(bK,{scope:n,type:r,dir:A,scrollHideDelay:s,scrollArea:c,viewport:p,onViewportChange:h,content:m,onContentChange:v,scrollbarX:b,onScrollbarXChange:w,scrollbarXEnabled:E,onScrollbarXEnabledChange:O,scrollbarY:y,onScrollbarYChange:S,scrollbarYEnabled:R,onScrollbarYEnabledChange:M,onCornerWidthChange:_,onCornerHeightChange:P},f.createElement(Nd.div,or({dir:A},a,{ref:T,style:{position:"relative","--radix-scroll-area-corner-width":k+"px","--radix-scroll-area-corner-height":I+"px",...e.style}})))}),xK="ScrollAreaViewport",wK=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,s=ds(xK,n),a=f.useRef(null),c=vl(t,a,s.onViewportChange);return f.createElement(f.Fragment,null,f.createElement("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"}}),f.createElement(Nd.div,or({"data-radix-scroll-area-viewport":""},o,{ref:c,style:{overflowX:s.scrollbarXEnabled?"scroll":"hidden",overflowY:s.scrollbarYEnabled?"scroll":"hidden",...e.style}}),f.createElement("div",{ref:s.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),Wa="ScrollAreaScrollbar",SK=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=ds(Wa,e.__scopeScrollArea),{onScrollbarXEnabledChange:s,onScrollbarYEnabledChange:a}=o,c=e.orientation==="horizontal";return f.useEffect(()=>(c?s(!0):a(!0),()=>{c?s(!1):a(!1)}),[c,s,a]),o.type==="hover"?f.createElement(CK,or({},r,{ref:t,forceMount:n})):o.type==="scroll"?f.createElement(kK,or({},r,{ref:t,forceMount:n})):o.type==="auto"?f.createElement(uI,or({},r,{ref:t,forceMount:n})):o.type==="always"?f.createElement(my,or({},r,{ref:t})):null}),CK=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=ds(Wa,e.__scopeScrollArea),[s,a]=f.useState(!1);return f.useEffect(()=>{const c=o.scrollArea;let d=0;if(c){const p=()=>{window.clearTimeout(d),a(!0)},h=()=>{d=window.setTimeout(()=>a(!1),o.scrollHideDelay)};return c.addEventListener("pointerenter",p),c.addEventListener("pointerleave",h),()=>{window.clearTimeout(d),c.removeEventListener("pointerenter",p),c.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),f.createElement($d,{present:n||s},f.createElement(uI,or({"data-state":s?"visible":"hidden"},r,{ref:t})))}),kK=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=ds(Wa,e.__scopeScrollArea),s=e.orientation==="horizontal",a=Tm(()=>d("SCROLL_END"),100),[c,d]=vK("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return f.useEffect(()=>{if(c==="idle"){const p=window.setTimeout(()=>d("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(p)}},[c,o.scrollHideDelay,d]),f.useEffect(()=>{const p=o.viewport,h=s?"scrollLeft":"scrollTop";if(p){let m=p[h];const v=()=>{const b=p[h];m!==b&&(d("SCROLL"),a()),m=b};return p.addEventListener("scroll",v),()=>p.removeEventListener("scroll",v)}},[o.viewport,s,d,a]),f.createElement($d,{present:n||c!=="hidden"},f.createElement(my,or({"data-state":c==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:Zi(e.onPointerEnter,()=>d("POINTER_ENTER")),onPointerLeave:Zi(e.onPointerLeave,()=>d("POINTER_LEAVE"))})))}),uI=f.forwardRef((e,t)=>{const n=ds(Wa,e.__scopeScrollArea),{forceMount:r,...o}=e,[s,a]=f.useState(!1),c=e.orientation==="horizontal",d=Tm(()=>{if(n.viewport){const p=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=ds(Wa,e.__scopeScrollArea),s=f.useRef(null),a=f.useRef(0),[c,d]=f.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),p=hI(c.viewport,c.content),h={...r,sizes:c,onSizesChange:d,hasThumb:p>0&&p<1,onThumbChange:v=>s.current=v,onThumbPointerUp:()=>a.current=0,onThumbPointerDown:v=>a.current=v};function m(v,b){return MK(v,a.current,c,b)}return n==="horizontal"?f.createElement(_K,or({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const v=o.viewport.scrollLeft,b=KC(v,c,o.dir);s.current.style.transform=`translate3d(${b}px, 0, 0)`}},onWheelScroll:v=>{o.viewport&&(o.viewport.scrollLeft=v)},onDragScroll:v=>{o.viewport&&(o.viewport.scrollLeft=m(v,o.dir))}})):n==="vertical"?f.createElement(PK,or({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&s.current){const v=o.viewport.scrollTop,b=KC(v,c);s.current.style.transform=`translate3d(0, ${b}px, 0)`}},onWheelScroll:v=>{o.viewport&&(o.viewport.scrollTop=v)},onDragScroll:v=>{o.viewport&&(o.viewport.scrollTop=m(v))}})):null}),_K=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=ds(Wa,e.__scopeScrollArea),[a,c]=f.useState(),d=f.useRef(null),p=vl(t,d,s.onScrollbarXChange);return f.useEffect(()=>{d.current&&c(getComputedStyle(d.current))},[d]),f.createElement(fI,or({"data-orientation":"horizontal"},o,{ref:p,sizes:n,style:{bottom:0,left:s.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:s.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Dm(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(s.viewport){const v=s.viewport.scrollLeft+h.deltaX;e.onWheelScroll(v),gI(v,m)&&h.preventDefault()}},onResize:()=>{d.current&&s.viewport&&a&&r({content:s.viewport.scrollWidth,viewport:s.viewport.offsetWidth,scrollbar:{size:d.current.clientWidth,paddingStart:vh(a.paddingLeft),paddingEnd:vh(a.paddingRight)}})}}))}),PK=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,s=ds(Wa,e.__scopeScrollArea),[a,c]=f.useState(),d=f.useRef(null),p=vl(t,d,s.onScrollbarYChange);return f.useEffect(()=>{d.current&&c(getComputedStyle(d.current))},[d]),f.createElement(fI,or({"data-orientation":"vertical"},o,{ref:p,sizes:n,style:{top:0,right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Dm(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(s.viewport){const v=s.viewport.scrollTop+h.deltaY;e.onWheelScroll(v),gI(v,m)&&h.preventDefault()}},onResize:()=>{d.current&&s.viewport&&a&&r({content:s.viewport.scrollHeight,viewport:s.viewport.offsetHeight,scrollbar:{size:d.current.clientHeight,paddingStart:vh(a.paddingTop),paddingEnd:vh(a.paddingBottom)}})}}))}),[jK,dI]=cI(Wa),fI=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:s,onThumbPointerUp:a,onThumbPointerDown:c,onThumbPositionChange:d,onDragScroll:p,onWheelScroll:h,onResize:m,...v}=e,b=ds(Wa,n),[w,y]=f.useState(null),S=vl(t,T=>y(T)),k=f.useRef(null),_=f.useRef(""),I=b.viewport,P=r.content-r.viewport,E=Ui(h),O=Ui(d),R=Tm(m,10);function M(T){if(k.current){const A=T.clientX-k.current.left,$=T.clientY-k.current.top;p({x:A,y:$})}}return f.useEffect(()=>{const T=A=>{const $=A.target;(w==null?void 0:w.contains($))&&E(A,P)};return document.addEventListener("wheel",T,{passive:!1}),()=>document.removeEventListener("wheel",T,{passive:!1})},[I,w,P,E]),f.useEffect(O,[r,O]),Cc(w,R),Cc(b.content,R),f.createElement(jK,{scope:n,scrollbar:w,hasThumb:o,onThumbChange:Ui(s),onThumbPointerUp:Ui(a),onThumbPositionChange:O,onThumbPointerDown:Ui(c)},f.createElement(Nd.div,or({},v,{ref:S,style:{position:"absolute",...v.style},onPointerDown:Zi(e.onPointerDown,T=>{T.button===0&&(T.target.setPointerCapture(T.pointerId),k.current=w.getBoundingClientRect(),_.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",M(T))}),onPointerMove:Zi(e.onPointerMove,M),onPointerUp:Zi(e.onPointerUp,T=>{const A=T.target;A.hasPointerCapture(T.pointerId)&&A.releasePointerCapture(T.pointerId),document.body.style.webkitUserSelect=_.current,k.current=null})})))}),u1="ScrollAreaThumb",IK=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=dI(u1,e.__scopeScrollArea);return f.createElement($d,{present:n||o.hasThumb},f.createElement(EK,or({ref:t},r)))}),EK=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,s=ds(u1,n),a=dI(u1,n),{onThumbPositionChange:c}=a,d=vl(t,m=>a.onThumbChange(m)),p=f.useRef(),h=Tm(()=>{p.current&&(p.current(),p.current=void 0)},100);return f.useEffect(()=>{const m=s.viewport;if(m){const v=()=>{if(h(),!p.current){const b=DK(m,c);p.current=b,c()}};return c(),m.addEventListener("scroll",v),()=>m.removeEventListener("scroll",v)}},[s.viewport,h,c]),f.createElement(Nd.div,or({"data-state":a.hasThumb?"visible":"hidden"},o,{ref:d,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Zi(e.onPointerDownCapture,m=>{const b=m.target.getBoundingClientRect(),w=m.clientX-b.left,y=m.clientY-b.top;a.onThumbPointerDown({x:w,y})}),onPointerUp:Zi(e.onPointerUp,a.onThumbPointerUp)}))}),pI="ScrollAreaCorner",OK=f.forwardRef((e,t)=>{const n=ds(pI,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?f.createElement(RK,or({},e,{ref:t})):null}),RK=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=ds(pI,n),[s,a]=f.useState(0),[c,d]=f.useState(0),p=!!(s&&c);return Cc(o.scrollbarX,()=>{var h;const m=((h=o.scrollbarX)===null||h===void 0?void 0:h.offsetHeight)||0;o.onCornerHeightChange(m),d(m)}),Cc(o.scrollbarY,()=>{var h;const m=((h=o.scrollbarY)===null||h===void 0?void 0:h.offsetWidth)||0;o.onCornerWidthChange(m),a(m)}),p?f.createElement(Nd.div,or({},r,{ref:t,style:{width:s,height:c,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function vh(e){return e?parseInt(e,10):0}function hI(e,t){const n=e/t;return isNaN(n)?0:n}function Dm(e){const t=hI(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function MK(e,t,n,r="ltr"){const o=Dm(n),s=o/2,a=t||s,c=o-a,d=n.scrollbar.paddingStart+a,p=n.scrollbar.size-n.scrollbar.paddingEnd-c,h=n.content-n.viewport,m=r==="ltr"?[0,h]:[h*-1,0];return mI([d,p],m)(e)}function KC(e,t,n="ltr"){const r=Dm(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,s=t.scrollbar.size-o,a=t.content-t.viewport,c=s-r,d=n==="ltr"?[0,a]:[a*-1,0],p=gK(e,d);return mI([0,a],[0,c])(p)}function mI(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function gI(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const s={left:e.scrollLeft,top:e.scrollTop},a=n.left!==s.left,c=n.top!==s.top;(a||c)&&t(),n=s,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function Tm(e,t){const n=Ui(e),r=f.useRef(0);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),f.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function Cc(e,t){const n=Ui(t);c1(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}const TK=yK,AK=wK,YC=SK,XC=IK,NK=OK;var $K=so((e,{scrollbarSize:t,offsetScrollbars:n,scrollbarHovered:r,hidden:o})=>({root:{overflow:"hidden"},viewport:{width:"100%",height:"100%",paddingRight:n?Ue(t):void 0,paddingBottom:n?Ue(t):void 0},scrollbar:{display:o?"none":"flex",userSelect:"none",touchAction:"none",boxSizing:"border-box",padding:`calc(${Ue(t)} / 5)`,transition:"background-color 150ms ease, opacity 150ms ease","&:hover":{backgroundColor:e.colorScheme==="dark"?e.colors.dark[8]:e.colors.gray[0],[`& .${tC("thumb")}`]:{backgroundColor:e.colorScheme==="dark"?e.fn.rgba(e.white,.5):e.fn.rgba(e.black,.5)}},'&[data-orientation="vertical"]':{width:Ue(t)},'&[data-orientation="horizontal"]':{flexDirection:"column",height:Ue(t)},'&[data-state="hidden"]':{display:"none",opacity:0}},thumb:{ref:tC("thumb"),flex:1,backgroundColor:e.colorScheme==="dark"?e.fn.rgba(e.white,.4):e.fn.rgba(e.black,.4),borderRadius:Ue(t),position:"relative",transition:"background-color 150ms ease",display:o?"none":void 0,overflow:"hidden","&::before":{content:'""',position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",width:"100%",height:"100%",minWidth:Ue(44),minHeight:Ue(44)}},corner:{backgroundColor:e.colorScheme==="dark"?e.colors.dark[6]:e.colors.gray[0],transition:"opacity 150ms ease",opacity:r?1:0,display:o?"none":void 0}}));const zK=$K;var LK=Object.defineProperty,BK=Object.defineProperties,FK=Object.getOwnPropertyDescriptors,bh=Object.getOwnPropertySymbols,vI=Object.prototype.hasOwnProperty,bI=Object.prototype.propertyIsEnumerable,QC=(e,t,n)=>t in e?LK(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,d1=(e,t)=>{for(var n in t||(t={}))vI.call(t,n)&&QC(e,n,t[n]);if(bh)for(var n of bh(t))bI.call(t,n)&&QC(e,n,t[n]);return e},yI=(e,t)=>BK(e,FK(t)),xI=(e,t)=>{var n={};for(var r in e)vI.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&bh)for(var r of bh(e))t.indexOf(r)<0&&bI.call(e,r)&&(n[r]=e[r]);return n};const wI={scrollbarSize:12,scrollHideDelay:1e3,type:"hover",offsetScrollbars:!1},Am=f.forwardRef((e,t)=>{const n=Sr("ScrollArea",wI,e),{children:r,className:o,classNames:s,styles:a,scrollbarSize:c,scrollHideDelay:d,type:p,dir:h,offsetScrollbars:m,viewportRef:v,onScrollPositionChange:b,unstyled:w,variant:y,viewportProps:S}=n,k=xI(n,["children","className","classNames","styles","scrollbarSize","scrollHideDelay","type","dir","offsetScrollbars","viewportRef","onScrollPositionChange","unstyled","variant","viewportProps"]),[_,I]=f.useState(!1),P=Fa(),{classes:E,cx:O}=zK({scrollbarSize:c,offsetScrollbars:m,scrollbarHovered:_,hidden:p==="never"},{name:"ScrollArea",classNames:s,styles:a,unstyled:w,variant:y});return F.createElement(TK,{type:p==="never"?"always":p,scrollHideDelay:d,dir:h||P.dir,ref:t,asChild:!0},F.createElement(Po,d1({className:O(E.root,o)},k),F.createElement(AK,yI(d1({},S),{className:E.viewport,ref:v,onScroll:typeof b=="function"?({currentTarget:R})=>b({x:R.scrollLeft,y:R.scrollTop}):void 0}),r),F.createElement(YC,{orientation:"horizontal",className:E.scrollbar,forceMount:!0,onMouseEnter:()=>I(!0),onMouseLeave:()=>I(!1)},F.createElement(XC,{className:E.thumb})),F.createElement(YC,{orientation:"vertical",className:E.scrollbar,forceMount:!0,onMouseEnter:()=>I(!0),onMouseLeave:()=>I(!1)},F.createElement(XC,{className:E.thumb})),F.createElement(NK,{className:E.corner})))}),SI=f.forwardRef((e,t)=>{const n=Sr("ScrollAreaAutosize",wI,e),{children:r,classNames:o,styles:s,scrollbarSize:a,scrollHideDelay:c,type:d,dir:p,offsetScrollbars:h,viewportRef:m,onScrollPositionChange:v,unstyled:b,sx:w,variant:y,viewportProps:S}=n,k=xI(n,["children","classNames","styles","scrollbarSize","scrollHideDelay","type","dir","offsetScrollbars","viewportRef","onScrollPositionChange","unstyled","sx","variant","viewportProps"]);return F.createElement(Po,yI(d1({},k),{ref:t,sx:[{display:"flex"},...cj(w)]}),F.createElement(Po,{sx:{display:"flex",flexDirection:"column",flex:1}},F.createElement(Am,{classNames:o,styles:s,scrollHideDelay:c,scrollbarSize:a,type:d,dir:p,offsetScrollbars:h,viewportRef:m,onScrollPositionChange:v,unstyled:b,variant:y,viewportProps:S},r)))});SI.displayName="@mantine/core/ScrollAreaAutosize";Am.displayName="@mantine/core/ScrollArea";Am.Autosize=SI;const CI=Am;var HK=Object.defineProperty,WK=Object.defineProperties,VK=Object.getOwnPropertyDescriptors,yh=Object.getOwnPropertySymbols,kI=Object.prototype.hasOwnProperty,_I=Object.prototype.propertyIsEnumerable,JC=(e,t,n)=>t in e?HK(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ZC=(e,t)=>{for(var n in t||(t={}))kI.call(t,n)&&JC(e,n,t[n]);if(yh)for(var n of yh(t))_I.call(t,n)&&JC(e,n,t[n]);return e},UK=(e,t)=>WK(e,VK(t)),GK=(e,t)=>{var n={};for(var r in e)kI.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&yh)for(var r of yh(e))t.indexOf(r)<0&&_I.call(e,r)&&(n[r]=e[r]);return n};const Nm=f.forwardRef((e,t)=>{var n=e,{style:r}=n,o=GK(n,["style"]);return F.createElement(CI,UK(ZC({},o),{style:ZC({width:"100%"},r),viewportProps:{tabIndex:-1},viewportRef:t}),o.children)});Nm.displayName="@mantine/core/SelectScrollArea";var qK=so(()=>({dropdown:{},itemsWrapper:{padding:Ue(4),display:"flex",width:"100%",boxSizing:"border-box"}}));const KK=qK;function Hc(e){return e.split("-")[1]}function gy(e){return e==="y"?"height":"width"}function js(e){return e.split("-")[0]}function Ei(e){return["top","bottom"].includes(js(e))?"x":"y"}function e4(e,t,n){let{reference:r,floating:o}=e;const s=r.x+r.width/2-o.width/2,a=r.y+r.height/2-o.height/2,c=Ei(t),d=gy(c),p=r[d]/2-o[d]/2,h=c==="x";let m;switch(js(t)){case"top":m={x:s,y:r.y-o.height};break;case"bottom":m={x:s,y:r.y+r.height};break;case"right":m={x:r.x+r.width,y:a};break;case"left":m={x:r.x-o.width,y:a};break;default:m={x:r.x,y:r.y}}switch(Hc(t)){case"start":m[c]-=p*(n&&h?-1:1);break;case"end":m[c]+=p*(n&&h?-1:1)}return m}const YK=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:a}=n,c=s.filter(Boolean),d=await(a.isRTL==null?void 0:a.isRTL(t));let p=await a.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:m}=e4(p,r,d),v=r,b={},w=0;for(let y=0;y({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:s,platform:a,elements:c}=t,{element:d,padding:p=0}=Aa(e,t)||{};if(d==null)return{};const h=vy(p),m={x:n,y:r},v=Ei(o),b=gy(v),w=await a.getDimensions(d),y=v==="y",S=y?"top":"left",k=y?"bottom":"right",_=y?"clientHeight":"clientWidth",I=s.reference[b]+s.reference[v]-m[v]-s.floating[b],P=m[v]-s.reference[v],E=await(a.getOffsetParent==null?void 0:a.getOffsetParent(d));let O=E?E[_]:0;O&&await(a.isElement==null?void 0:a.isElement(E))||(O=c.floating[_]||s.floating[b]);const R=I/2-P/2,M=O/2-w[b]/2-1,T=gi(h[S],M),A=gi(h[k],M),$=T,Q=O-w[b]-A,B=O/2-w[b]/2+R,V=f1($,B,Q),q=Hc(o)!=null&&B!=V&&s.reference[b]/2-(B<$?T:A)-w[b]/2<0?B<$?$-B:Q-B:0;return{[v]:m[v]-q,data:{[v]:V,centerOffset:B-V+q}}}}),XK=["top","right","bottom","left"];XK.reduce((e,t)=>e.concat(t,t+"-start",t+"-end"),[]);const QK={left:"right",right:"left",bottom:"top",top:"bottom"};function xh(e){return e.replace(/left|right|bottom|top/g,t=>QK[t])}function JK(e,t,n){n===void 0&&(n=!1);const r=Hc(e),o=Ei(e),s=gy(o);let a=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(a=xh(a)),{main:a,cross:xh(a)}}const ZK={start:"end",end:"start"};function G0(e){return e.replace(/start|end/g,t=>ZK[t])}const eY=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n;const{placement:r,middlewareData:o,rects:s,initialPlacement:a,platform:c,elements:d}=t,{mainAxis:p=!0,crossAxis:h=!0,fallbackPlacements:m,fallbackStrategy:v="bestFit",fallbackAxisSideDirection:b="none",flipAlignment:w=!0,...y}=Aa(e,t),S=js(r),k=js(a)===a,_=await(c.isRTL==null?void 0:c.isRTL(d.floating)),I=m||(k||!w?[xh(a)]:function($){const Q=xh($);return[G0($),Q,G0(Q)]}(a));m||b==="none"||I.push(...function($,Q,B,V){const q=Hc($);let G=function(D,L,W){const Y=["left","right"],ae=["right","left"],ye=["top","bottom"],ue=["bottom","top"];switch(D){case"top":case"bottom":return W?L?ae:Y:L?Y:ae;case"left":case"right":return L?ye:ue;default:return[]}}(js($),B==="start",V);return q&&(G=G.map(D=>D+"-"+q),Q&&(G=G.concat(G.map(G0)))),G}(a,w,b,_));const P=[a,...I],E=await by(t,y),O=[];let R=((n=o.flip)==null?void 0:n.overflows)||[];if(p&&O.push(E[S]),h){const{main:$,cross:Q}=JK(r,s,_);O.push(E[$],E[Q])}if(R=[...R,{placement:r,overflows:O}],!O.every($=>$<=0)){var M,T;const $=(((M=o.flip)==null?void 0:M.index)||0)+1,Q=P[$];if(Q)return{data:{index:$,overflows:R},reset:{placement:Q}};let B=(T=R.filter(V=>V.overflows[0]<=0).sort((V,q)=>V.overflows[1]-q.overflows[1])[0])==null?void 0:T.placement;if(!B)switch(v){case"bestFit":{var A;const V=(A=R.map(q=>[q.placement,q.overflows.filter(G=>G>0).reduce((G,D)=>G+D,0)]).sort((q,G)=>q[1]-G[1])[0])==null?void 0:A[0];V&&(B=V);break}case"initialPlacement":B=a}if(r!==B)return{reset:{placement:B}}}return{}}}};function n4(e){const t=gi(...e.map(r=>r.left)),n=gi(...e.map(r=>r.top));return{x:t,y:n,width:Ks(...e.map(r=>r.right))-t,height:Ks(...e.map(r=>r.bottom))-n}}const tY=function(e){return e===void 0&&(e={}),{name:"inline",options:e,async fn(t){const{placement:n,elements:r,rects:o,platform:s,strategy:a}=t,{padding:c=2,x:d,y:p}=Aa(e,t),h=Array.from(await(s.getClientRects==null?void 0:s.getClientRects(r.reference))||[]),m=function(y){const S=y.slice().sort((I,P)=>I.y-P.y),k=[];let _=null;for(let I=0;I_.height/2?k.push([P]):k[k.length-1].push(P),_=P}return k.map(I=>kc(n4(I)))}(h),v=kc(n4(h)),b=vy(c),w=await s.getElementRects({reference:{getBoundingClientRect:function(){if(m.length===2&&m[0].left>m[1].right&&d!=null&&p!=null)return m.find(y=>d>y.left-b.left&&dy.top-b.top&&p=2){if(Ei(n)==="x"){const E=m[0],O=m[m.length-1],R=js(n)==="top",M=E.top,T=O.bottom,A=R?E.left:O.left,$=R?E.right:O.right;return{top:M,bottom:T,left:A,right:$,width:$-A,height:T-M,x:A,y:M}}const y=js(n)==="left",S=Ks(...m.map(E=>E.right)),k=gi(...m.map(E=>E.left)),_=m.filter(E=>y?E.left===k:E.right===S),I=_[0].top,P=_[_.length-1].bottom;return{top:I,bottom:P,left:k,right:S,width:S-k,height:P-I,x:k,y:I}}return v}},floating:r.floating,strategy:a});return o.reference.x!==w.reference.x||o.reference.y!==w.reference.y||o.reference.width!==w.reference.width||o.reference.height!==w.reference.height?{reset:{rects:w}}:{}}}},nY=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await async function(s,a){const{placement:c,platform:d,elements:p}=s,h=await(d.isRTL==null?void 0:d.isRTL(p.floating)),m=js(c),v=Hc(c),b=Ei(c)==="x",w=["left","top"].includes(m)?-1:1,y=h&&b?-1:1,S=Aa(a,s);let{mainAxis:k,crossAxis:_,alignmentAxis:I}=typeof S=="number"?{mainAxis:S,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...S};return v&&typeof I=="number"&&(_=v==="end"?-1*I:I),b?{x:_*y,y:k*w}:{x:k*w,y:_*y}}(t,e);return{x:n+o.x,y:r+o.y,data:o}}}};function PI(e){return e==="x"?"y":"x"}const rY=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:s=!0,crossAxis:a=!1,limiter:c={fn:S=>{let{x:k,y:_}=S;return{x:k,y:_}}},...d}=Aa(e,t),p={x:n,y:r},h=await by(t,d),m=Ei(js(o)),v=PI(m);let b=p[m],w=p[v];if(s){const S=m==="y"?"bottom":"right";b=f1(b+h[m==="y"?"top":"left"],b,b-h[S])}if(a){const S=v==="y"?"bottom":"right";w=f1(w+h[v==="y"?"top":"left"],w,w-h[S])}const y=c.fn({...t,[m]:b,[v]:w});return{...y,data:{x:y.x-n,y:y.y-r}}}}},oY=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:s,middlewareData:a}=t,{offset:c=0,mainAxis:d=!0,crossAxis:p=!0}=Aa(e,t),h={x:n,y:r},m=Ei(o),v=PI(m);let b=h[m],w=h[v];const y=Aa(c,t),S=typeof y=="number"?{mainAxis:y,crossAxis:0}:{mainAxis:0,crossAxis:0,...y};if(d){const I=m==="y"?"height":"width",P=s.reference[m]-s.floating[I]+S.mainAxis,E=s.reference[m]+s.reference[I]-S.mainAxis;bE&&(b=E)}if(p){var k,_;const I=m==="y"?"width":"height",P=["top","left"].includes(js(o)),E=s.reference[v]-s.floating[I]+(P&&((k=a.offset)==null?void 0:k[v])||0)+(P?0:S.crossAxis),O=s.reference[v]+s.reference[I]+(P?0:((_=a.offset)==null?void 0:_[v])||0)-(P?S.crossAxis:0);wO&&(w=O)}return{[m]:b,[v]:w}}}},sY=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:s}=t,{apply:a=()=>{},...c}=Aa(e,t),d=await by(t,c),p=js(n),h=Hc(n),m=Ei(n)==="x",{width:v,height:b}=r.floating;let w,y;p==="top"||p==="bottom"?(w=p,y=h===(await(o.isRTL==null?void 0:o.isRTL(s.floating))?"start":"end")?"left":"right"):(y=p,w=h==="end"?"top":"bottom");const S=b-d[w],k=v-d[y],_=!t.middlewareData.shift;let I=S,P=k;if(m){const O=v-d.left-d.right;P=h||_?gi(k,O):O}else{const O=b-d.top-d.bottom;I=h||_?gi(S,O):O}if(_&&!h){const O=Ks(d.left,0),R=Ks(d.right,0),M=Ks(d.top,0),T=Ks(d.bottom,0);m?P=v-2*(O!==0||R!==0?O+R:Ks(d.left,d.right)):I=b-2*(M!==0||T!==0?M+T:Ks(d.top,d.bottom))}await a({...t,availableWidth:P,availableHeight:I});const E=await o.getDimensions(s.floating);return v!==E.width||b!==E.height?{reset:{rects:!0}}:{}}}};function $o(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function sa(e){return $o(e).getComputedStyle(e)}function jI(e){return e instanceof $o(e).Node}function vi(e){return jI(e)?(e.nodeName||"").toLowerCase():"#document"}function Ms(e){return e instanceof HTMLElement||e instanceof $o(e).HTMLElement}function r4(e){return typeof ShadowRoot<"u"&&(e instanceof $o(e).ShadowRoot||e instanceof ShadowRoot)}function od(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=sa(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function aY(e){return["table","td","th"].includes(vi(e))}function p1(e){const t=yy(),n=sa(e);return n.transform!=="none"||n.perspective!=="none"||!!n.containerType&&n.containerType!=="normal"||!t&&!!n.backdropFilter&&n.backdropFilter!=="none"||!t&&!!n.filter&&n.filter!=="none"||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function yy(){return!(typeof CSS>"u"||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}function $m(e){return["html","body","#document"].includes(vi(e))}const h1=Math.min,dc=Math.max,wh=Math.round,op=Math.floor,bi=e=>({x:e,y:e});function II(e){const t=sa(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ms(e),s=o?e.offsetWidth:n,a=o?e.offsetHeight:r,c=wh(n)!==s||wh(r)!==a;return c&&(n=s,r=a),{width:n,height:r,$:c}}function _a(e){return e instanceof Element||e instanceof $o(e).Element}function xy(e){return _a(e)?e:e.contextElement}function fc(e){const t=xy(e);if(!Ms(t))return bi(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:s}=II(t);let a=(s?wh(n.width):n.width)/r,c=(s?wh(n.height):n.height)/o;return a&&Number.isFinite(a)||(a=1),c&&Number.isFinite(c)||(c=1),{x:a,y:c}}const iY=bi(0);function EI(e){const t=$o(e);return yy()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:iY}function cl(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),s=xy(e);let a=bi(1);t&&(r?_a(r)&&(a=fc(r)):a=fc(e));const c=function(v,b,w){return b===void 0&&(b=!1),!(!w||b&&w!==$o(v))&&b}(s,n,r)?EI(s):bi(0);let d=(o.left+c.x)/a.x,p=(o.top+c.y)/a.y,h=o.width/a.x,m=o.height/a.y;if(s){const v=$o(s),b=r&&_a(r)?$o(r):r;let w=v.frameElement;for(;w&&r&&b!==v;){const y=fc(w),S=w.getBoundingClientRect(),k=getComputedStyle(w),_=S.left+(w.clientLeft+parseFloat(k.paddingLeft))*y.x,I=S.top+(w.clientTop+parseFloat(k.paddingTop))*y.y;d*=y.x,p*=y.y,h*=y.x,m*=y.y,d+=_,p+=I,w=$o(w).frameElement}}return kc({width:h,height:m,x:d,y:p})}function zm(e){return _a(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function Pa(e){var t;return(t=(jI(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OI(e){return cl(Pa(e)).left+zm(e).scrollLeft}function _c(e){if(vi(e)==="html")return e;const t=e.assignedSlot||e.parentNode||r4(e)&&e.host||Pa(e);return r4(t)?t.host:t}function RI(e){const t=_c(e);return $m(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ms(t)&&od(t)?t:RI(t)}function Sh(e,t){var n;t===void 0&&(t=[]);const r=RI(e),o=r===((n=e.ownerDocument)==null?void 0:n.body),s=$o(r);return o?t.concat(s,s.visualViewport||[],od(r)?r:[]):t.concat(r,Sh(r))}function o4(e,t,n){let r;if(t==="viewport")r=function(o,s){const a=$o(o),c=Pa(o),d=a.visualViewport;let p=c.clientWidth,h=c.clientHeight,m=0,v=0;if(d){p=d.width,h=d.height;const b=yy();(!b||b&&s==="fixed")&&(m=d.offsetLeft,v=d.offsetTop)}return{width:p,height:h,x:m,y:v}}(e,n);else if(t==="document")r=function(o){const s=Pa(o),a=zm(o),c=o.ownerDocument.body,d=dc(s.scrollWidth,s.clientWidth,c.scrollWidth,c.clientWidth),p=dc(s.scrollHeight,s.clientHeight,c.scrollHeight,c.clientHeight);let h=-a.scrollLeft+OI(o);const m=-a.scrollTop;return sa(c).direction==="rtl"&&(h+=dc(s.clientWidth,c.clientWidth)-d),{width:d,height:p,x:h,y:m}}(Pa(e));else if(_a(t))r=function(o,s){const a=cl(o,!0,s==="fixed"),c=a.top+o.clientTop,d=a.left+o.clientLeft,p=Ms(o)?fc(o):bi(1);return{width:o.clientWidth*p.x,height:o.clientHeight*p.y,x:d*p.x,y:c*p.y}}(t,n);else{const o=EI(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return kc(r)}function MI(e,t){const n=_c(e);return!(n===t||!_a(n)||$m(n))&&(sa(n).position==="fixed"||MI(n,t))}function lY(e,t,n){const r=Ms(t),o=Pa(t),s=n==="fixed",a=cl(e,!0,s,t);let c={scrollLeft:0,scrollTop:0};const d=bi(0);if(r||!r&&!s)if((vi(t)!=="body"||od(o))&&(c=zm(t)),Ms(t)){const p=cl(t,!0,s,t);d.x=p.x+t.clientLeft,d.y=p.y+t.clientTop}else o&&(d.x=OI(o));return{x:a.left+c.scrollLeft-d.x,y:a.top+c.scrollTop-d.y,width:a.width,height:a.height}}function s4(e,t){return Ms(e)&&sa(e).position!=="fixed"?t?t(e):e.offsetParent:null}function a4(e,t){const n=$o(e);if(!Ms(e))return n;let r=s4(e,t);for(;r&&aY(r)&&sa(r).position==="static";)r=s4(r,t);return r&&(vi(r)==="html"||vi(r)==="body"&&sa(r).position==="static"&&!p1(r))?n:r||function(o){let s=_c(o);for(;Ms(s)&&!$m(s);){if(p1(s))return s;s=_c(s)}return null}(e)||n}const cY={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=Ms(n),s=Pa(n);if(n===s)return t;let a={scrollLeft:0,scrollTop:0},c=bi(1);const d=bi(0);if((o||!o&&r!=="fixed")&&((vi(n)!=="body"||od(s))&&(a=zm(n)),Ms(n))){const p=cl(n);c=fc(n),d.x=p.x+n.clientLeft,d.y=p.y+n.clientTop}return{width:t.width*c.x,height:t.height*c.y,x:t.x*c.x-a.scrollLeft*c.x+d.x,y:t.y*c.y-a.scrollTop*c.y+d.y}},getDocumentElement:Pa,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?function(d,p){const h=p.get(d);if(h)return h;let m=Sh(d).filter(y=>_a(y)&&vi(y)!=="body"),v=null;const b=sa(d).position==="fixed";let w=b?_c(d):d;for(;_a(w)&&!$m(w);){const y=sa(w),S=p1(w);S||y.position!=="fixed"||(v=null),(b?!S&&!v:!S&&y.position==="static"&&v&&["absolute","fixed"].includes(v.position)||od(w)&&!S&&MI(d,w))?m=m.filter(k=>k!==w):v=y,w=_c(w)}return p.set(d,m),m}(t,this._c):[].concat(n),r],a=s[0],c=s.reduce((d,p)=>{const h=o4(t,p,o);return d.top=dc(h.top,d.top),d.right=h1(h.right,d.right),d.bottom=h1(h.bottom,d.bottom),d.left=dc(h.left,d.left),d},o4(t,a,o));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}},getOffsetParent:a4,getElementRects:async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||a4,s=this.getDimensions;return{reference:lY(t,await o(n),r),floating:{x:0,y:0,...await s(n)}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){return II(e)},getScale:fc,isElement:_a,isRTL:function(e){return getComputedStyle(e).direction==="rtl"}};function uY(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:c=typeof IntersectionObserver=="function",animationFrame:d=!1}=r,p=xy(e),h=o||s?[...p?Sh(p):[],...Sh(t)]:[];h.forEach(S=>{o&&S.addEventListener("scroll",n,{passive:!0}),s&&S.addEventListener("resize",n)});const m=p&&c?function(S,k){let _,I=null;const P=Pa(S);function E(){clearTimeout(_),I&&I.disconnect(),I=null}return function O(R,M){R===void 0&&(R=!1),M===void 0&&(M=1),E();const{left:T,top:A,width:$,height:Q}=S.getBoundingClientRect();if(R||k(),!$||!Q)return;const B={rootMargin:-op(A)+"px "+-op(P.clientWidth-(T+$))+"px "+-op(P.clientHeight-(A+Q))+"px "+-op(T)+"px",threshold:dc(0,h1(1,M))||1};let V=!0;function q(G){const D=G[0].intersectionRatio;if(D!==M){if(!V)return O();D?O(!1,D):_=setTimeout(()=>{O(!1,1e-7)},100)}V=!1}try{I=new IntersectionObserver(q,{...B,root:P.ownerDocument})}catch{I=new IntersectionObserver(q,B)}I.observe(S)}(!0),E}(p,n):null;let v,b=-1,w=null;a&&(w=new ResizeObserver(S=>{let[k]=S;k&&k.target===p&&w&&(w.unobserve(t),cancelAnimationFrame(b),b=requestAnimationFrame(()=>{w&&w.observe(t)})),n()}),p&&!d&&w.observe(p),w.observe(t));let y=d?cl(e):null;return d&&function S(){const k=cl(e);!y||k.x===y.x&&k.y===y.y&&k.width===y.width&&k.height===y.height||n(),y=k,v=requestAnimationFrame(S)}(),n(),()=>{h.forEach(S=>{o&&S.removeEventListener("scroll",n),s&&S.removeEventListener("resize",n)}),m&&m(),w&&w.disconnect(),w=null,d&&cancelAnimationFrame(v)}}const dY=(e,t,n)=>{const r=new Map,o={platform:cY,...n},s={...o.platform,_c:r};return YK(e,t,{...o,platform:s})},fY=e=>{const{element:t,padding:n}=e;function r(o){return Object.prototype.hasOwnProperty.call(o,"current")}return{name:"arrow",options:e,fn(o){return r(t)?t.current!=null?t4({element:t.current,padding:n}).fn(o):{}:t?t4({element:t,padding:n}).fn(o):{}}}};var jp=typeof document<"u"?f.useLayoutEffect:f.useEffect;function Ch(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!Ch(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!Object.prototype.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&e.$$typeof)&&!Ch(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function i4(e){const t=f.useRef(e);return jp(()=>{t.current=e}),t}function pY(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,whileElementsMounted:s,open:a}=e,[c,d]=f.useState({x:null,y:null,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[p,h]=f.useState(r);Ch(p,r)||h(r);const m=f.useRef(null),v=f.useRef(null),b=f.useRef(c),w=i4(s),y=i4(o),[S,k]=f.useState(null),[_,I]=f.useState(null),P=f.useCallback(A=>{m.current!==A&&(m.current=A,k(A))},[]),E=f.useCallback(A=>{v.current!==A&&(v.current=A,I(A))},[]),O=f.useCallback(()=>{if(!m.current||!v.current)return;const A={placement:t,strategy:n,middleware:p};y.current&&(A.platform=y.current),dY(m.current,v.current,A).then($=>{const Q={...$,isPositioned:!0};R.current&&!Ch(b.current,Q)&&(b.current=Q,_i.flushSync(()=>{d(Q)}))})},[p,t,n,y]);jp(()=>{a===!1&&b.current.isPositioned&&(b.current.isPositioned=!1,d(A=>({...A,isPositioned:!1})))},[a]);const R=f.useRef(!1);jp(()=>(R.current=!0,()=>{R.current=!1}),[]),jp(()=>{if(S&&_){if(w.current)return w.current(S,_,O);O()}},[S,_,O,w]);const M=f.useMemo(()=>({reference:m,floating:v,setReference:P,setFloating:E}),[P,E]),T=f.useMemo(()=>({reference:S,floating:_}),[S,_]);return f.useMemo(()=>({...c,update:O,refs:M,elements:T,reference:P,floating:E}),[c,O,M,T,P,E])}var hY=typeof document<"u"?f.useLayoutEffect:f.useEffect;function mY(){const e=new Map;return{emit(t,n){var r;(r=e.get(t))==null||r.forEach(o=>o(n))},on(t,n){e.set(t,[...e.get(t)||[],n])},off(t,n){e.set(t,(e.get(t)||[]).filter(r=>r!==n))}}}const gY=f.createContext(null),vY=()=>f.useContext(gY);function bY(e){return(e==null?void 0:e.ownerDocument)||document}function yY(e){return bY(e).defaultView||window}function sp(e){return e?e instanceof yY(e).Element:!1}const xY=N1["useInsertionEffect".toString()],wY=xY||(e=>e());function SY(e){const t=f.useRef(()=>{});return wY(()=>{t.current=e}),f.useCallback(function(){for(var n=arguments.length,r=new Array(n),o=0;omY())[0],[p,h]=f.useState(null),m=f.useCallback(k=>{const _=sp(k)?{getBoundingClientRect:()=>k.getBoundingClientRect(),contextElement:k}:k;o.refs.setReference(_)},[o.refs]),v=f.useCallback(k=>{(sp(k)||k===null)&&(a.current=k,h(k)),(sp(o.refs.reference.current)||o.refs.reference.current===null||k!==null&&!sp(k))&&o.refs.setReference(k)},[o.refs]),b=f.useMemo(()=>({...o.refs,setReference:v,setPositionReference:m,domReference:a}),[o.refs,v,m]),w=f.useMemo(()=>({...o.elements,domReference:p}),[o.elements,p]),y=SY(n),S=f.useMemo(()=>({...o,refs:b,elements:w,dataRef:c,nodeId:r,events:d,open:t,onOpenChange:y}),[o,r,d,t,y,b,w]);return hY(()=>{const k=s==null?void 0:s.nodesRef.current.find(_=>_.id===r);k&&(k.context=S)}),f.useMemo(()=>({...o,context:S,refs:b,reference:v,positionReference:m}),[o,b,S,v,m])}function kY({opened:e,floating:t,position:n,positionDependencies:r}){const[o,s]=f.useState(0);f.useEffect(()=>{if(t.refs.reference.current&&t.refs.floating.current)return uY(t.refs.reference.current,t.refs.floating.current,t.update)},[t.refs.reference.current,t.refs.floating.current,e,o,n]),Ps(()=>{t.update()},r),Ps(()=>{s(a=>a+1)},[e])}function _Y(e){const t=[nY(e.offset)];return e.middlewares.shift&&t.push(rY({limiter:oY()})),e.middlewares.flip&&t.push(eY()),e.middlewares.inline&&t.push(tY()),t.push(fY({element:e.arrowRef,padding:e.arrowOffset})),t}function PY(e){const[t,n]=rd({value:e.opened,defaultValue:e.defaultOpened,finalValue:!1,onChange:e.onChange}),r=()=>{var a;(a=e.onClose)==null||a.call(e),n(!1)},o=()=>{var a,c;t?((a=e.onClose)==null||a.call(e),n(!1)):((c=e.onOpen)==null||c.call(e),n(!0))},s=CY({placement:e.position,middleware:[..._Y(e),...e.width==="target"?[sY({apply({rects:a}){var c,d;Object.assign((d=(c=s.refs.floating.current)==null?void 0:c.style)!=null?d:{},{width:`${a.reference.width}px`})}})]:[]]});return kY({opened:e.opened,position:e.position,positionDependencies:e.positionDependencies,floating:s}),Ps(()=>{var a;(a=e.onPositionChange)==null||a.call(e,s.placement)},[s.placement]),Ps(()=>{var a,c;e.opened?(c=e.onOpen)==null||c.call(e):(a=e.onClose)==null||a.call(e)},[e.opened]),{floating:s,controlled:typeof e.opened=="boolean",opened:t,onClose:r,onToggle:o}}const DI={context:"Popover component was not found in the tree",children:"Popover.Target component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported"},[jY,TI]=hU(DI.context);var IY=Object.defineProperty,EY=Object.defineProperties,OY=Object.getOwnPropertyDescriptors,kh=Object.getOwnPropertySymbols,AI=Object.prototype.hasOwnProperty,NI=Object.prototype.propertyIsEnumerable,l4=(e,t,n)=>t in e?IY(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ap=(e,t)=>{for(var n in t||(t={}))AI.call(t,n)&&l4(e,n,t[n]);if(kh)for(var n of kh(t))NI.call(t,n)&&l4(e,n,t[n]);return e},RY=(e,t)=>EY(e,OY(t)),MY=(e,t)=>{var n={};for(var r in e)AI.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&kh)for(var r of kh(e))t.indexOf(r)<0&&NI.call(e,r)&&(n[r]=e[r]);return n};const DY={refProp:"ref",popupType:"dialog"},$I=f.forwardRef((e,t)=>{const n=Sr("PopoverTarget",DY,e),{children:r,refProp:o,popupType:s}=n,a=MY(n,["children","refProp","popupType"]);if(!dj(r))throw new Error(DI.children);const c=a,d=TI(),p=Ad(d.reference,r.ref,t),h=d.withRoles?{"aria-haspopup":s,"aria-expanded":d.opened,"aria-controls":d.getDropdownId(),id:d.getTargetId()}:{};return f.cloneElement(r,ap(RY(ap(ap(ap({},c),h),d.targetProps),{className:pj(d.targetProps.className,c.className,r.props.className),[o]:p}),d.controlled?null:{onClick:d.onToggle}))});$I.displayName="@mantine/core/PopoverTarget";var TY=so((e,{radius:t,shadow:n})=>({dropdown:{position:"absolute",backgroundColor:e.white,background:e.colorScheme==="dark"?e.colors.dark[6]:e.white,border:`${Ue(1)} solid ${e.colorScheme==="dark"?e.colors.dark[4]:e.colors.gray[2]}`,padding:`${e.spacing.sm} ${e.spacing.md}`,boxShadow:e.shadows[n]||n||"none",borderRadius:e.fn.radius(t),"&:focus":{outline:0}},arrow:{backgroundColor:"inherit",border:`${Ue(1)} solid ${e.colorScheme==="dark"?e.colors.dark[4]:e.colors.gray[2]}`,zIndex:1}}));const AY=TY;var NY=Object.defineProperty,c4=Object.getOwnPropertySymbols,$Y=Object.prototype.hasOwnProperty,zY=Object.prototype.propertyIsEnumerable,u4=(e,t,n)=>t in e?NY(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Bl=(e,t)=>{for(var n in t||(t={}))$Y.call(t,n)&&u4(e,n,t[n]);if(c4)for(var n of c4(t))zY.call(t,n)&&u4(e,n,t[n]);return e};const d4={entering:"in",entered:"in",exiting:"out",exited:"out","pre-exiting":"out","pre-entering":"out"};function LY({transition:e,state:t,duration:n,timingFunction:r}){const o={transitionDuration:`${n}ms`,transitionTimingFunction:r};return typeof e=="string"?e in Jf?Bl(Bl(Bl({transitionProperty:Jf[e].transitionProperty},o),Jf[e].common),Jf[e][d4[t]]):null:Bl(Bl(Bl({transitionProperty:e.transitionProperty},o),e.common),e[d4[t]])}function BY({duration:e,exitDuration:t,timingFunction:n,mounted:r,onEnter:o,onExit:s,onEntered:a,onExited:c}){const d=Fa(),p=xj(),h=d.respectReducedMotion?p:!1,[m,v]=f.useState(h?0:e),[b,w]=f.useState(r?"entered":"exited"),y=f.useRef(-1),S=k=>{const _=k?o:s,I=k?a:c;w(k?"pre-entering":"pre-exiting"),window.clearTimeout(y.current);const P=h?0:k?e:t;if(v(P),P===0)typeof _=="function"&&_(),typeof I=="function"&&I(),w(k?"entered":"exited");else{const E=window.setTimeout(()=>{typeof _=="function"&&_(),w(k?"entering":"exiting")},10);y.current=window.setTimeout(()=>{window.clearTimeout(E),typeof I=="function"&&I(),w(k?"entered":"exited")},P)}};return Ps(()=>{S(r)},[r]),f.useEffect(()=>()=>window.clearTimeout(y.current),[]),{transitionDuration:m,transitionStatus:b,transitionTimingFunction:n||d.transitionTimingFunction}}function zI({keepMounted:e,transition:t,duration:n=250,exitDuration:r=n,mounted:o,children:s,timingFunction:a,onExit:c,onEntered:d,onEnter:p,onExited:h}){const{transitionDuration:m,transitionStatus:v,transitionTimingFunction:b}=BY({mounted:o,exitDuration:r,duration:n,timingFunction:a,onExit:c,onEntered:d,onEnter:p,onExited:h});return m===0?o?F.createElement(F.Fragment,null,s({})):e?s({display:"none"}):null:v==="exited"?e?s({display:"none"}):null:F.createElement(F.Fragment,null,s(LY({transition:t,duration:m,state:v,timingFunction:b})))}zI.displayName="@mantine/core/Transition";function LI({children:e,active:t=!0,refProp:n="ref"}){const r=KU(t),o=Ad(r,e==null?void 0:e.ref);return dj(e)?f.cloneElement(e,{[n]:o}):e}LI.displayName="@mantine/core/FocusTrap";var FY=Object.defineProperty,HY=Object.defineProperties,WY=Object.getOwnPropertyDescriptors,f4=Object.getOwnPropertySymbols,VY=Object.prototype.hasOwnProperty,UY=Object.prototype.propertyIsEnumerable,p4=(e,t,n)=>t in e?FY(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Za=(e,t)=>{for(var n in t||(t={}))VY.call(t,n)&&p4(e,n,t[n]);if(f4)for(var n of f4(t))UY.call(t,n)&&p4(e,n,t[n]);return e},ip=(e,t)=>HY(e,WY(t));function h4(e,t,n,r){return e==="center"||r==="center"?{top:t}:e==="end"?{bottom:n}:e==="start"?{top:n}:{}}function m4(e,t,n,r,o){return e==="center"||r==="center"?{left:t}:e==="end"?{[o==="ltr"?"right":"left"]:n}:e==="start"?{[o==="ltr"?"left":"right"]:n}:{}}const GY={bottom:"borderTopLeftRadius",left:"borderTopRightRadius",right:"borderBottomLeftRadius",top:"borderBottomRightRadius"};function qY({position:e,arrowSize:t,arrowOffset:n,arrowRadius:r,arrowPosition:o,arrowX:s,arrowY:a,dir:c}){const[d,p="center"]=e.split("-"),h={width:Ue(t),height:Ue(t),transform:"rotate(45deg)",position:"absolute",[GY[d]]:Ue(r)},m=Ue(-t/2);return d==="left"?ip(Za(Za({},h),h4(p,a,n,o)),{right:m,borderLeftColor:"transparent",borderBottomColor:"transparent"}):d==="right"?ip(Za(Za({},h),h4(p,a,n,o)),{left:m,borderRightColor:"transparent",borderTopColor:"transparent"}):d==="top"?ip(Za(Za({},h),m4(p,s,n,o,c)),{bottom:m,borderTopColor:"transparent",borderLeftColor:"transparent"}):d==="bottom"?ip(Za(Za({},h),m4(p,s,n,o,c)),{top:m,borderBottomColor:"transparent",borderRightColor:"transparent"}):{}}var KY=Object.defineProperty,YY=Object.defineProperties,XY=Object.getOwnPropertyDescriptors,_h=Object.getOwnPropertySymbols,BI=Object.prototype.hasOwnProperty,FI=Object.prototype.propertyIsEnumerable,g4=(e,t,n)=>t in e?KY(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,QY=(e,t)=>{for(var n in t||(t={}))BI.call(t,n)&&g4(e,n,t[n]);if(_h)for(var n of _h(t))FI.call(t,n)&&g4(e,n,t[n]);return e},JY=(e,t)=>YY(e,XY(t)),ZY=(e,t)=>{var n={};for(var r in e)BI.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&_h)for(var r of _h(e))t.indexOf(r)<0&&FI.call(e,r)&&(n[r]=e[r]);return n};const HI=f.forwardRef((e,t)=>{var n=e,{position:r,arrowSize:o,arrowOffset:s,arrowRadius:a,arrowPosition:c,visible:d,arrowX:p,arrowY:h}=n,m=ZY(n,["position","arrowSize","arrowOffset","arrowRadius","arrowPosition","visible","arrowX","arrowY"]);const v=Fa();return d?F.createElement("div",JY(QY({},m),{ref:t,style:qY({position:r,arrowSize:o,arrowOffset:s,arrowRadius:a,arrowPosition:c,dir:v.dir,arrowX:p,arrowY:h})})):null});HI.displayName="@mantine/core/FloatingArrow";var eX=Object.defineProperty,tX=Object.defineProperties,nX=Object.getOwnPropertyDescriptors,Ph=Object.getOwnPropertySymbols,WI=Object.prototype.hasOwnProperty,VI=Object.prototype.propertyIsEnumerable,v4=(e,t,n)=>t in e?eX(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Fl=(e,t)=>{for(var n in t||(t={}))WI.call(t,n)&&v4(e,n,t[n]);if(Ph)for(var n of Ph(t))VI.call(t,n)&&v4(e,n,t[n]);return e},lp=(e,t)=>tX(e,nX(t)),rX=(e,t)=>{var n={};for(var r in e)WI.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Ph)for(var r of Ph(e))t.indexOf(r)<0&&VI.call(e,r)&&(n[r]=e[r]);return n};const oX={};function UI(e){var t;const n=Sr("PopoverDropdown",oX,e),{style:r,className:o,children:s,onKeyDownCapture:a}=n,c=rX(n,["style","className","children","onKeyDownCapture"]),d=TI(),{classes:p,cx:h}=AY({radius:d.radius,shadow:d.shadow},{name:d.__staticSelector,classNames:d.classNames,styles:d.styles,unstyled:d.unstyled,variant:d.variant}),m=FU({opened:d.opened,shouldReturnFocus:d.returnFocus}),v=d.withRoles?{"aria-labelledby":d.getTargetId(),id:d.getDropdownId(),role:"dialog"}:{};return d.disabled?null:F.createElement(Uj,lp(Fl({},d.portalProps),{withinPortal:d.withinPortal}),F.createElement(zI,lp(Fl({mounted:d.opened},d.transitionProps),{transition:d.transitionProps.transition||"fade",duration:(t=d.transitionProps.duration)!=null?t:150,keepMounted:d.keepMounted,exitDuration:typeof d.transitionProps.exitDuration=="number"?d.transitionProps.exitDuration:d.transitionProps.duration}),b=>{var w,y;return F.createElement(LI,{active:d.trapFocus},F.createElement(Po,Fl(lp(Fl({},v),{tabIndex:-1,ref:d.floating,style:lp(Fl(Fl({},r),b),{zIndex:d.zIndex,top:(w=d.y)!=null?w:0,left:(y=d.x)!=null?y:0,width:d.width==="target"?void 0:Ue(d.width)}),className:h(p.dropdown,o),onKeyDownCapture:gU(d.onClose,{active:d.closeOnEscape,onTrigger:m,onKeyDown:a}),"data-position":d.placement}),c),s,F.createElement(HI,{ref:d.arrowRef,arrowX:d.arrowX,arrowY:d.arrowY,visible:d.withArrow,position:d.placement,arrowSize:d.arrowSize,arrowRadius:d.arrowRadius,arrowOffset:d.arrowOffset,arrowPosition:d.arrowPosition,className:p.arrow})))}))}UI.displayName="@mantine/core/PopoverDropdown";function sX(e,t){if(e==="rtl"&&(t.includes("right")||t.includes("left"))){const[n,r]=t.split("-"),o=n==="right"?"left":"right";return r===void 0?o:`${o}-${r}`}return t}var b4=Object.getOwnPropertySymbols,aX=Object.prototype.hasOwnProperty,iX=Object.prototype.propertyIsEnumerable,lX=(e,t)=>{var n={};for(var r in e)aX.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&b4)for(var r of b4(e))t.indexOf(r)<0&&iX.call(e,r)&&(n[r]=e[r]);return n};const cX={position:"bottom",offset:8,positionDependencies:[],transitionProps:{transition:"fade",duration:150},middlewares:{flip:!0,shift:!0,inline:!1},arrowSize:7,arrowOffset:5,arrowRadius:0,arrowPosition:"side",closeOnClickOutside:!0,withinPortal:!1,closeOnEscape:!0,trapFocus:!1,withRoles:!0,returnFocus:!1,clickOutsideEvents:["mousedown","touchstart"],zIndex:uy("popover"),__staticSelector:"Popover",width:"max-content"};function Wc(e){var t,n,r,o,s,a;const c=f.useRef(null),d=Sr("Popover",cX,e),{children:p,position:h,offset:m,onPositionChange:v,positionDependencies:b,opened:w,transitionProps:y,width:S,middlewares:k,withArrow:_,arrowSize:I,arrowOffset:P,arrowRadius:E,arrowPosition:O,unstyled:R,classNames:M,styles:T,closeOnClickOutside:A,withinPortal:$,portalProps:Q,closeOnEscape:B,clickOutsideEvents:V,trapFocus:q,onClose:G,onOpen:D,onChange:L,zIndex:W,radius:Y,shadow:ae,id:ye,defaultOpened:ue,__staticSelector:X,withRoles:K,disabled:U,returnFocus:se,variant:re,keepMounted:oe}=d,pe=lX(d,["children","position","offset","onPositionChange","positionDependencies","opened","transitionProps","width","middlewares","withArrow","arrowSize","arrowOffset","arrowRadius","arrowPosition","unstyled","classNames","styles","closeOnClickOutside","withinPortal","portalProps","closeOnEscape","clickOutsideEvents","trapFocus","onClose","onOpen","onChange","zIndex","radius","shadow","id","defaultOpened","__staticSelector","withRoles","disabled","returnFocus","variant","keepMounted"]),[le,ge]=f.useState(null),[_e,ie]=f.useState(null),Se=fy(ye),Fe=Fa(),Ae=PY({middlewares:k,width:S,position:sX(Fe.dir,h),offset:typeof m=="number"?m+(_?I/2:0):m,arrowRef:c,arrowOffset:P,onPositionChange:v,positionDependencies:b,opened:w,defaultOpened:ue,onChange:L,onOpen:D,onClose:G});$U(()=>Ae.opened&&A&&Ae.onClose(),V,[le,_e]);const He=f.useCallback(ct=>{ge(ct),Ae.floating.reference(ct)},[Ae.floating.reference]),Ct=f.useCallback(ct=>{ie(ct),Ae.floating.floating(ct)},[Ae.floating.floating]);return F.createElement(jY,{value:{returnFocus:se,disabled:U,controlled:Ae.controlled,reference:He,floating:Ct,x:Ae.floating.x,y:Ae.floating.y,arrowX:(r=(n=(t=Ae.floating)==null?void 0:t.middlewareData)==null?void 0:n.arrow)==null?void 0:r.x,arrowY:(a=(s=(o=Ae.floating)==null?void 0:o.middlewareData)==null?void 0:s.arrow)==null?void 0:a.y,opened:Ae.opened,arrowRef:c,transitionProps:y,width:S,withArrow:_,arrowSize:I,arrowOffset:P,arrowRadius:E,arrowPosition:O,placement:Ae.floating.placement,trapFocus:q,withinPortal:$,portalProps:Q,zIndex:W,radius:Y,shadow:ae,closeOnEscape:B,onClose:Ae.onClose,onToggle:Ae.onToggle,getTargetId:()=>`${Se}-target`,getDropdownId:()=>`${Se}-dropdown`,withRoles:K,targetProps:pe,__staticSelector:X,classNames:M,styles:T,unstyled:R,variant:re,keepMounted:oe}},p)}Wc.Target=$I;Wc.Dropdown=UI;Wc.displayName="@mantine/core/Popover";var uX=Object.defineProperty,jh=Object.getOwnPropertySymbols,GI=Object.prototype.hasOwnProperty,qI=Object.prototype.propertyIsEnumerable,y4=(e,t,n)=>t in e?uX(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,dX=(e,t)=>{for(var n in t||(t={}))GI.call(t,n)&&y4(e,n,t[n]);if(jh)for(var n of jh(t))qI.call(t,n)&&y4(e,n,t[n]);return e},fX=(e,t)=>{var n={};for(var r in e)GI.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&jh)for(var r of jh(e))t.indexOf(r)<0&&qI.call(e,r)&&(n[r]=e[r]);return n};function pX(e){var t=e,{children:n,component:r="div",maxHeight:o=220,direction:s="column",id:a,innerRef:c,__staticSelector:d,styles:p,classNames:h,unstyled:m}=t,v=fX(t,["children","component","maxHeight","direction","id","innerRef","__staticSelector","styles","classNames","unstyled"]);const{classes:b}=KK(null,{name:d,styles:p,classNames:h,unstyled:m});return F.createElement(Wc.Dropdown,dX({p:0,onMouseDown:w=>w.preventDefault()},v),F.createElement("div",{style:{maxHeight:Ue(o),display:"flex"}},F.createElement(Po,{component:r||"div",id:`${a}-items`,"aria-labelledby":`${a}-label`,role:"listbox",onMouseDown:w=>w.preventDefault(),style:{flex:1,overflowY:r!==Nm?"auto":void 0},"data-combobox-popover":!0,tabIndex:-1,ref:c},F.createElement("div",{className:b.itemsWrapper,style:{flexDirection:s}},n))))}function hi({opened:e,transitionProps:t={transition:"fade",duration:0},shadow:n,withinPortal:r,portalProps:o,children:s,__staticSelector:a,onDirectionChange:c,switchDirectionOnFlip:d,zIndex:p,dropdownPosition:h,positionDependencies:m=[],classNames:v,styles:b,unstyled:w,readOnly:y,variant:S}){return F.createElement(Wc,{unstyled:w,classNames:v,styles:b,width:"target",withRoles:!1,opened:e,middlewares:{flip:h==="flip",shift:!1},position:h==="flip"?"bottom":h,positionDependencies:m,zIndex:p,__staticSelector:a,withinPortal:r,portalProps:o,transitionProps:t,shadow:n,disabled:y,onPositionChange:k=>d&&(c==null?void 0:c(k==="top"?"column-reverse":"column")),variant:S},s)}hi.Target=Wc.Target;hi.Dropdown=pX;var hX=Object.defineProperty,mX=Object.defineProperties,gX=Object.getOwnPropertyDescriptors,Ih=Object.getOwnPropertySymbols,KI=Object.prototype.hasOwnProperty,YI=Object.prototype.propertyIsEnumerable,x4=(e,t,n)=>t in e?hX(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,cp=(e,t)=>{for(var n in t||(t={}))KI.call(t,n)&&x4(e,n,t[n]);if(Ih)for(var n of Ih(t))YI.call(t,n)&&x4(e,n,t[n]);return e},vX=(e,t)=>mX(e,gX(t)),bX=(e,t)=>{var n={};for(var r in e)KI.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Ih)for(var r of Ih(e))t.indexOf(r)<0&&YI.call(e,r)&&(n[r]=e[r]);return n};function XI(e,t,n){const r=Sr(e,t,n),{label:o,description:s,error:a,required:c,classNames:d,styles:p,className:h,unstyled:m,__staticSelector:v,sx:b,errorProps:w,labelProps:y,descriptionProps:S,wrapperProps:k,id:_,size:I,style:P,inputContainer:E,inputWrapperOrder:O,withAsterisk:R,variant:M}=r,T=bX(r,["label","description","error","required","classNames","styles","className","unstyled","__staticSelector","sx","errorProps","labelProps","descriptionProps","wrapperProps","id","size","style","inputContainer","inputWrapperOrder","withAsterisk","variant"]),A=fy(_),{systemStyles:$,rest:Q}=Mm(T),B=cp({label:o,description:s,error:a,required:c,classNames:d,className:h,__staticSelector:v,sx:b,errorProps:w,labelProps:y,descriptionProps:S,unstyled:m,styles:p,id:A,size:I,style:P,inputContainer:E,inputWrapperOrder:O,withAsterisk:R,variant:M},k);return vX(cp({},Q),{classNames:d,styles:p,unstyled:m,wrapperProps:cp(cp({},B),$),inputProps:{required:c,classNames:d,styles:p,unstyled:m,id:A,size:I,__staticSelector:v,error:a,variant:M}})}var yX=so((e,t,{size:n})=>({label:{display:"inline-block",fontSize:Wt({size:n,sizes:e.fontSizes}),fontWeight:500,color:e.colorScheme==="dark"?e.colors.dark[0]:e.colors.gray[9],wordBreak:"break-word",cursor:"default",WebkitTapHighlightColor:"transparent"},required:{color:e.fn.variant({variant:"filled",color:"red"}).background}}));const xX=yX;var wX=Object.defineProperty,Eh=Object.getOwnPropertySymbols,QI=Object.prototype.hasOwnProperty,JI=Object.prototype.propertyIsEnumerable,w4=(e,t,n)=>t in e?wX(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,SX=(e,t)=>{for(var n in t||(t={}))QI.call(t,n)&&w4(e,n,t[n]);if(Eh)for(var n of Eh(t))JI.call(t,n)&&w4(e,n,t[n]);return e},CX=(e,t)=>{var n={};for(var r in e)QI.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Eh)for(var r of Eh(e))t.indexOf(r)<0&&JI.call(e,r)&&(n[r]=e[r]);return n};const kX={labelElement:"label",size:"sm"},wy=f.forwardRef((e,t)=>{const n=Sr("InputLabel",kX,e),{labelElement:r,children:o,required:s,size:a,classNames:c,styles:d,unstyled:p,className:h,htmlFor:m,__staticSelector:v,variant:b,onMouseDown:w}=n,y=CX(n,["labelElement","children","required","size","classNames","styles","unstyled","className","htmlFor","__staticSelector","variant","onMouseDown"]),{classes:S,cx:k}=xX(null,{name:["InputWrapper",v],classNames:c,styles:d,unstyled:p,variant:b,size:a});return F.createElement(Po,SX({component:r,ref:t,className:k(S.label,h),htmlFor:r==="label"?m:void 0,onMouseDown:_=>{w==null||w(_),!_.defaultPrevented&&_.detail>1&&_.preventDefault()}},y),o,s&&F.createElement("span",{className:S.required,"aria-hidden":!0}," *"))});wy.displayName="@mantine/core/InputLabel";var _X=so((e,t,{size:n})=>({error:{wordBreak:"break-word",color:e.fn.variant({variant:"filled",color:"red"}).background,fontSize:`calc(${Wt({size:n,sizes:e.fontSizes})} - ${Ue(2)})`,lineHeight:1.2,display:"block"}}));const PX=_X;var jX=Object.defineProperty,Oh=Object.getOwnPropertySymbols,ZI=Object.prototype.hasOwnProperty,eE=Object.prototype.propertyIsEnumerable,S4=(e,t,n)=>t in e?jX(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,IX=(e,t)=>{for(var n in t||(t={}))ZI.call(t,n)&&S4(e,n,t[n]);if(Oh)for(var n of Oh(t))eE.call(t,n)&&S4(e,n,t[n]);return e},EX=(e,t)=>{var n={};for(var r in e)ZI.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Oh)for(var r of Oh(e))t.indexOf(r)<0&&eE.call(e,r)&&(n[r]=e[r]);return n};const OX={size:"sm"},Sy=f.forwardRef((e,t)=>{const n=Sr("InputError",OX,e),{children:r,className:o,classNames:s,styles:a,unstyled:c,size:d,__staticSelector:p,variant:h}=n,m=EX(n,["children","className","classNames","styles","unstyled","size","__staticSelector","variant"]),{classes:v,cx:b}=PX(null,{name:["InputWrapper",p],classNames:s,styles:a,unstyled:c,variant:h,size:d});return F.createElement(Sc,IX({className:b(v.error,o),ref:t},m),r)});Sy.displayName="@mantine/core/InputError";var RX=so((e,t,{size:n})=>({description:{wordBreak:"break-word",color:e.colorScheme==="dark"?e.colors.dark[2]:e.colors.gray[6],fontSize:`calc(${Wt({size:n,sizes:e.fontSizes})} - ${Ue(2)})`,lineHeight:1.2,display:"block"}}));const MX=RX;var DX=Object.defineProperty,Rh=Object.getOwnPropertySymbols,tE=Object.prototype.hasOwnProperty,nE=Object.prototype.propertyIsEnumerable,C4=(e,t,n)=>t in e?DX(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,TX=(e,t)=>{for(var n in t||(t={}))tE.call(t,n)&&C4(e,n,t[n]);if(Rh)for(var n of Rh(t))nE.call(t,n)&&C4(e,n,t[n]);return e},AX=(e,t)=>{var n={};for(var r in e)tE.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Rh)for(var r of Rh(e))t.indexOf(r)<0&&nE.call(e,r)&&(n[r]=e[r]);return n};const NX={size:"sm"},Cy=f.forwardRef((e,t)=>{const n=Sr("InputDescription",NX,e),{children:r,className:o,classNames:s,styles:a,unstyled:c,size:d,__staticSelector:p,variant:h}=n,m=AX(n,["children","className","classNames","styles","unstyled","size","__staticSelector","variant"]),{classes:v,cx:b}=MX(null,{name:["InputWrapper",p],classNames:s,styles:a,unstyled:c,variant:h,size:d});return F.createElement(Sc,TX({color:"dimmed",className:b(v.description,o),ref:t,unstyled:c},m),r)});Cy.displayName="@mantine/core/InputDescription";const rE=f.createContext({offsetBottom:!1,offsetTop:!1,describedBy:void 0}),$X=rE.Provider,zX=()=>f.useContext(rE);function LX(e,{hasDescription:t,hasError:n}){const r=e.findIndex(d=>d==="input"),o=e[r-1],s=e[r+1];return{offsetBottom:t&&s==="description"||n&&s==="error",offsetTop:t&&o==="description"||n&&o==="error"}}var BX=Object.defineProperty,FX=Object.defineProperties,HX=Object.getOwnPropertyDescriptors,k4=Object.getOwnPropertySymbols,WX=Object.prototype.hasOwnProperty,VX=Object.prototype.propertyIsEnumerable,_4=(e,t,n)=>t in e?BX(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,UX=(e,t)=>{for(var n in t||(t={}))WX.call(t,n)&&_4(e,n,t[n]);if(k4)for(var n of k4(t))VX.call(t,n)&&_4(e,n,t[n]);return e},GX=(e,t)=>FX(e,HX(t)),qX=so(e=>({root:GX(UX({},e.fn.fontStyles()),{lineHeight:e.lineHeight})}));const KX=qX;var YX=Object.defineProperty,XX=Object.defineProperties,QX=Object.getOwnPropertyDescriptors,Mh=Object.getOwnPropertySymbols,oE=Object.prototype.hasOwnProperty,sE=Object.prototype.propertyIsEnumerable,P4=(e,t,n)=>t in e?YX(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ei=(e,t)=>{for(var n in t||(t={}))oE.call(t,n)&&P4(e,n,t[n]);if(Mh)for(var n of Mh(t))sE.call(t,n)&&P4(e,n,t[n]);return e},j4=(e,t)=>XX(e,QX(t)),JX=(e,t)=>{var n={};for(var r in e)oE.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Mh)for(var r of Mh(e))t.indexOf(r)<0&&sE.call(e,r)&&(n[r]=e[r]);return n};const ZX={labelElement:"label",size:"sm",inputContainer:e=>e,inputWrapperOrder:["label","description","input","error"]},aE=f.forwardRef((e,t)=>{const n=Sr("InputWrapper",ZX,e),{className:r,label:o,children:s,required:a,id:c,error:d,description:p,labelElement:h,labelProps:m,descriptionProps:v,errorProps:b,classNames:w,styles:y,size:S,inputContainer:k,__staticSelector:_,unstyled:I,inputWrapperOrder:P,withAsterisk:E,variant:O}=n,R=JX(n,["className","label","children","required","id","error","description","labelElement","labelProps","descriptionProps","errorProps","classNames","styles","size","inputContainer","__staticSelector","unstyled","inputWrapperOrder","withAsterisk","variant"]),{classes:M,cx:T}=KX(null,{classNames:w,styles:y,name:["InputWrapper",_],unstyled:I,variant:O,size:S}),A={classNames:w,styles:y,unstyled:I,size:S,variant:O,__staticSelector:_},$=typeof E=="boolean"?E:a,Q=c?`${c}-error`:b==null?void 0:b.id,B=c?`${c}-description`:v==null?void 0:v.id,q=`${!!d&&typeof d!="boolean"?Q:""} ${p?B:""}`,G=q.trim().length>0?q.trim():void 0,D=o&&F.createElement(wy,ei(ei({key:"label",labelElement:h,id:c?`${c}-label`:void 0,htmlFor:c,required:$},A),m),o),L=p&&F.createElement(Cy,j4(ei(ei({key:"description"},v),A),{size:(v==null?void 0:v.size)||A.size,id:(v==null?void 0:v.id)||B}),p),W=F.createElement(f.Fragment,{key:"input"},k(s)),Y=typeof d!="boolean"&&d&&F.createElement(Sy,j4(ei(ei({},b),A),{size:(b==null?void 0:b.size)||A.size,key:"error",id:(b==null?void 0:b.id)||Q}),d),ae=P.map(ye=>{switch(ye){case"label":return D;case"input":return W;case"description":return L;case"error":return Y;default:return null}});return F.createElement($X,{value:ei({describedBy:G},LX(P,{hasDescription:!!L,hasError:!!Y}))},F.createElement(Po,ei({className:T(M.root,r),ref:t},R),ae))});aE.displayName="@mantine/core/InputWrapper";var eQ=Object.defineProperty,Dh=Object.getOwnPropertySymbols,iE=Object.prototype.hasOwnProperty,lE=Object.prototype.propertyIsEnumerable,I4=(e,t,n)=>t in e?eQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,tQ=(e,t)=>{for(var n in t||(t={}))iE.call(t,n)&&I4(e,n,t[n]);if(Dh)for(var n of Dh(t))lE.call(t,n)&&I4(e,n,t[n]);return e},nQ=(e,t)=>{var n={};for(var r in e)iE.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Dh)for(var r of Dh(e))t.indexOf(r)<0&&lE.call(e,r)&&(n[r]=e[r]);return n};const rQ={},cE=f.forwardRef((e,t)=>{const n=Sr("InputPlaceholder",rQ,e),{sx:r}=n,o=nQ(n,["sx"]);return F.createElement(Po,tQ({component:"span",sx:[s=>s.fn.placeholderStyles(),...cj(r)],ref:t},o))});cE.displayName="@mantine/core/InputPlaceholder";var oQ=Object.defineProperty,sQ=Object.defineProperties,aQ=Object.getOwnPropertyDescriptors,E4=Object.getOwnPropertySymbols,iQ=Object.prototype.hasOwnProperty,lQ=Object.prototype.propertyIsEnumerable,O4=(e,t,n)=>t in e?oQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,up=(e,t)=>{for(var n in t||(t={}))iQ.call(t,n)&&O4(e,n,t[n]);if(E4)for(var n of E4(t))lQ.call(t,n)&&O4(e,n,t[n]);return e},q0=(e,t)=>sQ(e,aQ(t));const Xo={xs:Ue(30),sm:Ue(36),md:Ue(42),lg:Ue(50),xl:Ue(60)},cQ=["default","filled","unstyled"];function uQ({theme:e,variant:t}){return cQ.includes(t)?t==="default"?{border:`${Ue(1)} solid ${e.colorScheme==="dark"?e.colors.dark[4]:e.colors.gray[4]}`,backgroundColor:e.colorScheme==="dark"?e.colors.dark[6]:e.white,transition:"border-color 100ms ease","&:focus, &:focus-within":e.focusRingStyles.inputStyles(e)}:t==="filled"?{border:`${Ue(1)} solid transparent`,backgroundColor:e.colorScheme==="dark"?e.colors.dark[5]:e.colors.gray[1],"&:focus, &:focus-within":e.focusRingStyles.inputStyles(e)}:{borderWidth:0,color:e.colorScheme==="dark"?e.colors.dark[0]:e.black,backgroundColor:"transparent",minHeight:Ue(28),outline:0,"&:focus, &:focus-within":{outline:"none",borderColor:"transparent"},"&:disabled":{backgroundColor:"transparent","&:focus, &:focus-within":{outline:"none",borderColor:"transparent"}}}:null}var dQ=so((e,{multiline:t,radius:n,invalid:r,rightSectionWidth:o,withRightSection:s,iconWidth:a,offsetBottom:c,offsetTop:d,pointer:p},{variant:h,size:m})=>{const v=e.fn.variant({variant:"filled",color:"red"}).background,b=h==="default"||h==="filled"?{minHeight:Wt({size:m,sizes:Xo}),paddingLeft:`calc(${Wt({size:m,sizes:Xo})} / 3)`,paddingRight:s?o||Wt({size:m,sizes:Xo}):`calc(${Wt({size:m,sizes:Xo})} / 3)`,borderRadius:e.fn.radius(n)}:h==="unstyled"&&s?{paddingRight:o||Wt({size:m,sizes:Xo})}:null;return{wrapper:{position:"relative",marginTop:d?`calc(${e.spacing.xs} / 2)`:void 0,marginBottom:c?`calc(${e.spacing.xs} / 2)`:void 0,"&:has(input:disabled)":{"& .mantine-Input-rightSection":{display:"none"}}},input:q0(up(up(q0(up({},e.fn.fontStyles()),{height:t?h==="unstyled"?void 0:"auto":Wt({size:m,sizes:Xo}),WebkitTapHighlightColor:"transparent",lineHeight:t?e.lineHeight:`calc(${Wt({size:m,sizes:Xo})} - ${Ue(2)})`,appearance:"none",resize:"none",boxSizing:"border-box",fontSize:Wt({size:m,sizes:e.fontSizes}),width:"100%",color:e.colorScheme==="dark"?e.colors.dark[0]:e.black,display:"block",textAlign:"left",cursor:p?"pointer":void 0}),uQ({theme:e,variant:h})),b),{"&:disabled, &[data-disabled]":{backgroundColor:e.colorScheme==="dark"?e.colors.dark[6]:e.colors.gray[1],color:e.colors.dark[2],opacity:.6,cursor:"not-allowed",pointerEvents:"none","&::placeholder":{color:e.colors.dark[2]}},"&[data-invalid]":{color:v,borderColor:v,"&::placeholder":{opacity:1,color:v}},"&[data-with-icon]":{paddingLeft:typeof a=="number"?Ue(a):Wt({size:m,sizes:Xo})},"&::placeholder":q0(up({},e.fn.placeholderStyles()),{opacity:1}),"&::-webkit-inner-spin-button, &::-webkit-outer-spin-button, &::-webkit-search-decoration, &::-webkit-search-cancel-button, &::-webkit-search-results-button, &::-webkit-search-results-decoration":{appearance:"none"},"&[type=number]":{MozAppearance:"textfield"}}),icon:{pointerEvents:"none",position:"absolute",zIndex:1,left:0,top:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",width:a?Ue(a):Wt({size:m,sizes:Xo}),color:r?e.colors.red[e.colorScheme==="dark"?6:7]:e.colorScheme==="dark"?e.colors.dark[2]:e.colors.gray[5]},rightSection:{position:"absolute",top:0,bottom:0,right:0,display:"flex",alignItems:"center",justifyContent:"center",width:o||Wt({size:m,sizes:Xo})}}});const fQ=dQ;var pQ=Object.defineProperty,hQ=Object.defineProperties,mQ=Object.getOwnPropertyDescriptors,Th=Object.getOwnPropertySymbols,uE=Object.prototype.hasOwnProperty,dE=Object.prototype.propertyIsEnumerable,R4=(e,t,n)=>t in e?pQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,dp=(e,t)=>{for(var n in t||(t={}))uE.call(t,n)&&R4(e,n,t[n]);if(Th)for(var n of Th(t))dE.call(t,n)&&R4(e,n,t[n]);return e},M4=(e,t)=>hQ(e,mQ(t)),gQ=(e,t)=>{var n={};for(var r in e)uE.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Th)for(var r of Th(e))t.indexOf(r)<0&&dE.call(e,r)&&(n[r]=e[r]);return n};const vQ={size:"sm",variant:"default"},bl=f.forwardRef((e,t)=>{const n=Sr("Input",vQ,e),{className:r,error:o,required:s,disabled:a,variant:c,icon:d,style:p,rightSectionWidth:h,iconWidth:m,rightSection:v,rightSectionProps:b,radius:w,size:y,wrapperProps:S,classNames:k,styles:_,__staticSelector:I,multiline:P,sx:E,unstyled:O,pointer:R}=n,M=gQ(n,["className","error","required","disabled","variant","icon","style","rightSectionWidth","iconWidth","rightSection","rightSectionProps","radius","size","wrapperProps","classNames","styles","__staticSelector","multiline","sx","unstyled","pointer"]),{offsetBottom:T,offsetTop:A,describedBy:$}=zX(),{classes:Q,cx:B}=fQ({radius:w,multiline:P,invalid:!!o,rightSectionWidth:h?Ue(h):void 0,iconWidth:m,withRightSection:!!v,offsetBottom:T,offsetTop:A,pointer:R},{classNames:k,styles:_,name:["Input",I],unstyled:O,variant:c,size:y}),{systemStyles:V,rest:q}=Mm(M);return F.createElement(Po,dp(dp({className:B(Q.wrapper,r),sx:E,style:p},V),S),d&&F.createElement("div",{className:Q.icon},d),F.createElement(Po,M4(dp({component:"input"},q),{ref:t,required:s,"aria-invalid":!!o,"aria-describedby":$,disabled:a,"data-disabled":a||void 0,"data-with-icon":!!d||void 0,"data-invalid":!!o||void 0,className:Q.input})),v&&F.createElement("div",M4(dp({},b),{className:Q.rightSection}),v))});bl.displayName="@mantine/core/Input";bl.Wrapper=aE;bl.Label=wy;bl.Description=Cy;bl.Error=Sy;bl.Placeholder=cE;const Pc=bl;var bQ=Object.defineProperty,Ah=Object.getOwnPropertySymbols,fE=Object.prototype.hasOwnProperty,pE=Object.prototype.propertyIsEnumerable,D4=(e,t,n)=>t in e?bQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,T4=(e,t)=>{for(var n in t||(t={}))fE.call(t,n)&&D4(e,n,t[n]);if(Ah)for(var n of Ah(t))pE.call(t,n)&&D4(e,n,t[n]);return e},yQ=(e,t)=>{var n={};for(var r in e)fE.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Ah)for(var r of Ah(e))t.indexOf(r)<0&&pE.call(e,r)&&(n[r]=e[r]);return n};const xQ={multiple:!1},hE=f.forwardRef((e,t)=>{const n=Sr("FileButton",xQ,e),{onChange:r,children:o,multiple:s,accept:a,name:c,form:d,resetRef:p,disabled:h,capture:m,inputProps:v}=n,b=yQ(n,["onChange","children","multiple","accept","name","form","resetRef","disabled","capture","inputProps"]),w=f.useRef(),y=()=>{!h&&w.current.click()},S=_=>{r(s?Array.from(_.currentTarget.files):_.currentTarget.files[0]||null)};return yj(p,()=>{w.current.value=""}),F.createElement(F.Fragment,null,o(T4({onClick:y},b)),F.createElement("input",T4({style:{display:"none"},type:"file",accept:a,multiple:s,onChange:S,ref:Ad(t,w),name:c,form:d,capture:m},v)))});hE.displayName="@mantine/core/FileButton";const mE={xs:Ue(16),sm:Ue(22),md:Ue(26),lg:Ue(30),xl:Ue(36)},wQ={xs:Ue(10),sm:Ue(12),md:Ue(14),lg:Ue(16),xl:Ue(18)};var SQ=so((e,{disabled:t,radius:n,readOnly:r},{size:o,variant:s})=>({defaultValue:{display:"flex",alignItems:"center",backgroundColor:t?e.colorScheme==="dark"?e.colors.dark[5]:e.colors.gray[3]:e.colorScheme==="dark"?e.colors.dark[7]:s==="filled"?e.white:e.colors.gray[1],color:t?e.colorScheme==="dark"?e.colors.dark[1]:e.colors.gray[7]:e.colorScheme==="dark"?e.colors.dark[0]:e.colors.gray[7],height:Wt({size:o,sizes:mE}),paddingLeft:`calc(${Wt({size:o,sizes:e.spacing})} / 1.5)`,paddingRight:t||r?Wt({size:o,sizes:e.spacing}):0,fontWeight:500,fontSize:Wt({size:o,sizes:wQ}),borderRadius:Wt({size:n,sizes:e.radius}),cursor:t?"not-allowed":"default",userSelect:"none",maxWidth:`calc(100% - ${Ue(10)})`},defaultValueRemove:{color:e.colorScheme==="dark"?e.colors.dark[0]:e.colors.gray[7],marginLeft:`calc(${Wt({size:o,sizes:e.spacing})} / 6)`},defaultValueLabel:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}));const CQ=SQ;var kQ=Object.defineProperty,Nh=Object.getOwnPropertySymbols,gE=Object.prototype.hasOwnProperty,vE=Object.prototype.propertyIsEnumerable,A4=(e,t,n)=>t in e?kQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_Q=(e,t)=>{for(var n in t||(t={}))gE.call(t,n)&&A4(e,n,t[n]);if(Nh)for(var n of Nh(t))vE.call(t,n)&&A4(e,n,t[n]);return e},PQ=(e,t)=>{var n={};for(var r in e)gE.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Nh)for(var r of Nh(e))t.indexOf(r)<0&&vE.call(e,r)&&(n[r]=e[r]);return n};const jQ={xs:16,sm:22,md:24,lg:26,xl:30};function bE(e){var t=e,{label:n,classNames:r,styles:o,className:s,onRemove:a,disabled:c,readOnly:d,size:p,radius:h="sm",variant:m,unstyled:v}=t,b=PQ(t,["label","classNames","styles","className","onRemove","disabled","readOnly","size","radius","variant","unstyled"]);const{classes:w,cx:y}=CQ({disabled:c,readOnly:d,radius:h},{name:"MultiSelect",classNames:r,styles:o,unstyled:v,size:p,variant:m});return F.createElement("div",_Q({className:y(w.defaultValue,s)},b),F.createElement("span",{className:w.defaultValueLabel},n),!c&&!d&&F.createElement(Jj,{"aria-hidden":!0,onMouseDown:a,size:jQ[p],radius:2,color:"blue",variant:"transparent",iconSize:"70%",className:w.defaultValueRemove,tabIndex:-1,unstyled:v}))}bE.displayName="@mantine/core/MultiSelect/DefaultValue";function IQ({data:e,searchable:t,limit:n,searchValue:r,filter:o,value:s,disableSelectedItemFiltering:a}){if(!t&&s.length===0)return e;if(!t){const d=[];for(let p=0;ph===e[p].value&&!e[p].disabled))&&d.push(e[p]);return d}const c=[];for(let d=0;dp===e[d].value&&!e[d].disabled),e[d])&&c.push(e[d]),!(c.length>=n));d+=1);return c}var EQ=Object.defineProperty,$h=Object.getOwnPropertySymbols,yE=Object.prototype.hasOwnProperty,xE=Object.prototype.propertyIsEnumerable,N4=(e,t,n)=>t in e?EQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,$4=(e,t)=>{for(var n in t||(t={}))yE.call(t,n)&&N4(e,n,t[n]);if($h)for(var n of $h(t))xE.call(t,n)&&N4(e,n,t[n]);return e},OQ=(e,t)=>{var n={};for(var r in e)yE.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&$h)for(var r of $h(e))t.indexOf(r)<0&&xE.call(e,r)&&(n[r]=e[r]);return n};const RQ={xs:Ue(14),sm:Ue(18),md:Ue(20),lg:Ue(24),xl:Ue(28)};function MQ(e){var t=e,{size:n,error:r,style:o}=t,s=OQ(t,["size","error","style"]);const a=Fa(),c=Wt({size:n,sizes:RQ});return F.createElement("svg",$4({viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:$4({color:r?a.colors.red[6]:a.colors.gray[6],width:c,height:c},o),"data-chevron":!0},s),F.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:"currentColor",fillRule:"evenodd",clipRule:"evenodd"}))}var DQ=Object.defineProperty,TQ=Object.defineProperties,AQ=Object.getOwnPropertyDescriptors,z4=Object.getOwnPropertySymbols,NQ=Object.prototype.hasOwnProperty,$Q=Object.prototype.propertyIsEnumerable,L4=(e,t,n)=>t in e?DQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,zQ=(e,t)=>{for(var n in t||(t={}))NQ.call(t,n)&&L4(e,n,t[n]);if(z4)for(var n of z4(t))$Q.call(t,n)&&L4(e,n,t[n]);return e},LQ=(e,t)=>TQ(e,AQ(t));function wE({shouldClear:e,clearButtonProps:t,onClear:n,size:r,error:o}){return e?F.createElement(Jj,LQ(zQ({},t),{variant:"transparent",onClick:n,size:r,onMouseDown:s=>s.preventDefault()})):F.createElement(MQ,{error:o,size:r})}wE.displayName="@mantine/core/SelectRightSection";var BQ=Object.defineProperty,FQ=Object.defineProperties,HQ=Object.getOwnPropertyDescriptors,zh=Object.getOwnPropertySymbols,SE=Object.prototype.hasOwnProperty,CE=Object.prototype.propertyIsEnumerable,B4=(e,t,n)=>t in e?BQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,K0=(e,t)=>{for(var n in t||(t={}))SE.call(t,n)&&B4(e,n,t[n]);if(zh)for(var n of zh(t))CE.call(t,n)&&B4(e,n,t[n]);return e},F4=(e,t)=>FQ(e,HQ(t)),WQ=(e,t)=>{var n={};for(var r in e)SE.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&zh)for(var r of zh(e))t.indexOf(r)<0&&CE.call(e,r)&&(n[r]=e[r]);return n};function kE(e){var t=e,{styles:n,rightSection:r,rightSectionWidth:o,theme:s}=t,a=WQ(t,["styles","rightSection","rightSectionWidth","theme"]);if(r)return{rightSection:r,rightSectionWidth:o,styles:n};const c=typeof n=="function"?n(s):n;return{rightSection:!a.readOnly&&!(a.disabled&&a.shouldClear)&&F.createElement(wE,K0({},a)),styles:F4(K0({},c),{rightSection:F4(K0({},c==null?void 0:c.rightSection),{pointerEvents:a.shouldClear?void 0:"none"})})}}var VQ=Object.defineProperty,UQ=Object.defineProperties,GQ=Object.getOwnPropertyDescriptors,H4=Object.getOwnPropertySymbols,qQ=Object.prototype.hasOwnProperty,KQ=Object.prototype.propertyIsEnumerable,W4=(e,t,n)=>t in e?VQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,YQ=(e,t)=>{for(var n in t||(t={}))qQ.call(t,n)&&W4(e,n,t[n]);if(H4)for(var n of H4(t))KQ.call(t,n)&&W4(e,n,t[n]);return e},XQ=(e,t)=>UQ(e,GQ(t)),QQ=so((e,{invalid:t},{size:n})=>({wrapper:{position:"relative","&:has(input:disabled)":{cursor:"not-allowed",pointerEvents:"none","& .mantine-MultiSelect-input":{backgroundColor:e.colorScheme==="dark"?e.colors.dark[6]:e.colors.gray[1],color:e.colors.dark[2],opacity:.6,"&::placeholder":{color:e.colors.dark[2]}},"& .mantine-MultiSelect-defaultValue":{backgroundColor:e.colorScheme==="dark"?e.colors.dark[5]:e.colors.gray[3],color:e.colorScheme==="dark"?e.colors.dark[1]:e.colors.gray[7]}}},values:{minHeight:`calc(${Wt({size:n,sizes:Xo})} - ${Ue(2)})`,display:"flex",alignItems:"center",flexWrap:"wrap",marginLeft:`calc(-${e.spacing.xs} / 2)`,boxSizing:"border-box","&[data-clearable]":{marginRight:Wt({size:n,sizes:Xo})}},value:{margin:`calc(${e.spacing.xs} / 2 - ${Ue(2)}) calc(${e.spacing.xs} / 2)`},searchInput:XQ(YQ({},e.fn.fontStyles()),{flex:1,minWidth:Ue(60),backgroundColor:"transparent",border:0,outline:0,fontSize:Wt({size:n,sizes:e.fontSizes}),padding:0,marginLeft:`calc(${e.spacing.xs} / 2)`,appearance:"none",color:"inherit",maxHeight:Wt({size:n,sizes:mE}),"&::placeholder":{opacity:1,color:t?e.colors.red[e.fn.primaryShade()]:e.colorScheme==="dark"?e.colors.dark[3]:e.colors.gray[5]},"&:disabled":{cursor:"not-allowed",pointerEvents:"none"}}),searchInputEmpty:{width:"100%"},searchInputInputHidden:{flex:0,width:0,minWidth:0,margin:0,overflow:"hidden"},searchInputPointer:{cursor:"pointer","&:disabled":{cursor:"not-allowed",pointerEvents:"none"}},input:{cursor:"pointer","&:disabled":{cursor:"not-allowed",pointerEvents:"none"}}}));const JQ=QQ;var ZQ=Object.defineProperty,eJ=Object.defineProperties,tJ=Object.getOwnPropertyDescriptors,Lh=Object.getOwnPropertySymbols,_E=Object.prototype.hasOwnProperty,PE=Object.prototype.propertyIsEnumerable,V4=(e,t,n)=>t in e?ZQ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Hl=(e,t)=>{for(var n in t||(t={}))_E.call(t,n)&&V4(e,n,t[n]);if(Lh)for(var n of Lh(t))PE.call(t,n)&&V4(e,n,t[n]);return e},U4=(e,t)=>eJ(e,tJ(t)),nJ=(e,t)=>{var n={};for(var r in e)_E.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Lh)for(var r of Lh(e))t.indexOf(r)<0&&PE.call(e,r)&&(n[r]=e[r]);return n};function rJ(e,t,n){return t?!1:n.label.toLowerCase().trim().includes(e.toLowerCase().trim())}function oJ(e,t){return!!e&&!t.some(n=>n.value.toLowerCase()===e.toLowerCase())}function G4(e,t){if(!Array.isArray(e))return;if(t.length===0)return[];const n=t.map(r=>typeof r=="object"?r.value:r);return e.filter(r=>n.includes(r))}const sJ={size:"sm",valueComponent:bE,itemComponent:hy,transitionProps:{transition:"fade",duration:0},maxDropdownHeight:220,shadow:"sm",searchable:!1,filter:rJ,limit:1/0,clearSearchOnChange:!0,clearable:!1,clearSearchOnBlur:!1,disabled:!1,initiallyOpened:!1,creatable:!1,shouldCreate:oJ,switchDirectionOnFlip:!1,zIndex:uy("popover"),selectOnBlur:!1,positionDependencies:[],dropdownPosition:"flip"},jE=f.forwardRef((e,t)=>{const n=Sr("MultiSelect",sJ,e),{className:r,style:o,required:s,label:a,description:c,size:d,error:p,classNames:h,styles:m,wrapperProps:v,value:b,defaultValue:w,data:y,onChange:S,valueComponent:k,itemComponent:_,id:I,transitionProps:P,maxDropdownHeight:E,shadow:O,nothingFound:R,onFocus:M,onBlur:T,searchable:A,placeholder:$,filter:Q,limit:B,clearSearchOnChange:V,clearable:q,clearSearchOnBlur:G,variant:D,onSearchChange:L,searchValue:W,disabled:Y,initiallyOpened:ae,radius:ye,icon:ue,rightSection:X,rightSectionWidth:K,creatable:U,getCreateLabel:se,shouldCreate:re,onCreate:oe,sx:pe,dropdownComponent:le,onDropdownClose:ge,onDropdownOpen:_e,maxSelectedValues:ie,withinPortal:Se,portalProps:Fe,switchDirectionOnFlip:Ae,zIndex:He,selectOnBlur:Ct,name:ct,dropdownPosition:on,errorProps:vt,labelProps:bt,descriptionProps:we,form:Re,positionDependencies:Pt,onKeyDown:At,unstyled:xe,inputContainer:ht,inputWrapperOrder:$t,readOnly:zt,withAsterisk:Ne,clearButtonProps:qe,hoverOnSearchChange:Pn,disableSelectedItemFiltering:Pe}=n,Je=nJ(n,["className","style","required","label","description","size","error","classNames","styles","wrapperProps","value","defaultValue","data","onChange","valueComponent","itemComponent","id","transitionProps","maxDropdownHeight","shadow","nothingFound","onFocus","onBlur","searchable","placeholder","filter","limit","clearSearchOnChange","clearable","clearSearchOnBlur","variant","onSearchChange","searchValue","disabled","initiallyOpened","radius","icon","rightSection","rightSectionWidth","creatable","getCreateLabel","shouldCreate","onCreate","sx","dropdownComponent","onDropdownClose","onDropdownOpen","maxSelectedValues","withinPortal","portalProps","switchDirectionOnFlip","zIndex","selectOnBlur","name","dropdownPosition","errorProps","labelProps","descriptionProps","form","positionDependencies","onKeyDown","unstyled","inputContainer","inputWrapperOrder","readOnly","withAsterisk","clearButtonProps","hoverOnSearchChange","disableSelectedItemFiltering"]),{classes:Xe,cx:dt,theme:Lt}=JQ({invalid:!!p},{name:"MultiSelect",classNames:h,styles:m,unstyled:xe,size:d,variant:D}),{systemStyles:lr,rest:pn}=Mm(Je),ln=f.useRef(),Fr=f.useRef({}),br=fy(I),[Fn,Hn]=f.useState(ae),[Wn,Ar]=f.useState(-1),[Ro,Hr]=f.useState("column"),[Wr,fs]=rd({value:W,defaultValue:"",finalValue:void 0,onChange:L}),[Nr,$s]=f.useState(!1),{scrollIntoView:ps,targetRef:ua,scrollableRef:zs}=wj({duration:0,offset:5,cancelable:!1,isList:!0}),J=U&&typeof se=="function";let ee=null;const he=y.map($e=>typeof $e=="string"?{label:$e,value:$e}:$e),ke=uj({data:he}),[me,ut]=rd({value:G4(b,y),defaultValue:G4(w,y),finalValue:[],onChange:S}),st=f.useRef(!!ie&&ie{if(!zt){const yt=me.filter(Mt=>Mt!==$e);ut(yt),ie&&yt.length{fs($e.currentTarget.value),!Y&&!st.current&&A&&Hn(!0)},xt=$e=>{typeof M=="function"&&M($e),!Y&&!st.current&&A&&Hn(!0)},Be=IQ({data:ke,searchable:A,searchValue:Wr,limit:B,filter:Q,value:me,disableSelectedItemFiltering:Pe});J&&re(Wr,ke)&&(ee=se(Wr),Be.push({label:Wr,value:Wr,creatable:!0}));const Ce=Math.min(Wn,Be.length-1),Qe=($e,yt,Mt)=>{let Ht=$e;for(;Mt(Ht);)if(Ht=yt(Ht),!Be[Ht].disabled)return Ht;return $e};Ps(()=>{Ar(Pn&&Wr?0:-1)},[Wr,Pn]),Ps(()=>{!Y&&me.length>y.length&&Hn(!1),ie&&me.length=ie&&(st.current=!0,Hn(!1))},[me]);const jt=$e=>{if(!zt)if(V&&fs(""),me.includes($e.value))Ft($e.value);else{if($e.creatable&&typeof oe=="function"){const yt=oe($e.value);typeof yt<"u"&&yt!==null&&ut(typeof yt=="string"?[...me,yt]:[...me,yt.value])}else ut([...me,$e.value]);me.length===ie-1&&(st.current=!0,Hn(!1)),Be.length===1&&Hn(!1)}},Et=$e=>{typeof T=="function"&&T($e),Ct&&Be[Ce]&&Fn&&jt(Be[Ce]),G&&fs(""),Hn(!1)},Nt=$e=>{if(Nr||(At==null||At($e),zt)||$e.key!=="Backspace"&&ie&&st.current)return;const yt=Ro==="column",Mt=()=>{Ar(jn=>{var Ut;const un=Qe(jn,sn=>sn+1,sn=>sn{Ar(jn=>{var Ut;const un=Qe(jn,sn=>sn-1,sn=>sn>0);return Fn&&(ua.current=Fr.current[(Ut=Be[un])==null?void 0:Ut.value],ps({alignment:yt?"start":"end"})),un})};switch($e.key){case"ArrowUp":{$e.preventDefault(),Hn(!0),yt?Ht():Mt();break}case"ArrowDown":{$e.preventDefault(),Hn(!0),yt?Mt():Ht();break}case"Enter":{$e.preventDefault(),Be[Ce]&&Fn?jt(Be[Ce]):Hn(!0);break}case" ":{A||($e.preventDefault(),Be[Ce]&&Fn?jt(Be[Ce]):Hn(!0));break}case"Backspace":{me.length>0&&Wr.length===0&&(ut(me.slice(0,-1)),Hn(!0),ie&&(st.current=!1));break}case"Home":{if(!A){$e.preventDefault(),Fn||Hn(!0);const jn=Be.findIndex(Ut=>!Ut.disabled);Ar(jn),ps({alignment:yt?"end":"start"})}break}case"End":{if(!A){$e.preventDefault(),Fn||Hn(!0);const jn=Be.map(Ut=>!!Ut.disabled).lastIndexOf(!1);Ar(jn),ps({alignment:yt?"end":"start"})}break}case"Escape":Hn(!1)}},Gt=me.map($e=>{let yt=ke.find(Mt=>Mt.value===$e&&!Mt.disabled);return!yt&&J&&(yt={value:$e,label:$e}),yt}).filter($e=>!!$e).map(($e,yt)=>F.createElement(k,U4(Hl({},$e),{variant:D,disabled:Y,className:Xe.value,readOnly:zt,onRemove:Mt=>{Mt.preventDefault(),Mt.stopPropagation(),Ft($e.value)},key:$e.value,size:d,styles:m,classNames:h,radius:ye,index:yt}))),Zt=$e=>me.includes($e),Jt=()=>{var $e;fs(""),ut([]),($e=ln.current)==null||$e.focus(),ie&&(st.current=!1)},Vt=!zt&&(Be.length>0?Fn:Fn&&!!R);return Ps(()=>{const $e=Vt?_e:ge;typeof $e=="function"&&$e()},[Vt]),F.createElement(Pc.Wrapper,Hl(Hl({required:s,id:br,label:a,error:p,description:c,size:d,className:r,style:o,classNames:h,styles:m,__staticSelector:"MultiSelect",sx:pe,errorProps:vt,descriptionProps:we,labelProps:bt,inputContainer:ht,inputWrapperOrder:$t,unstyled:xe,withAsterisk:Ne,variant:D},lr),v),F.createElement(hi,{opened:Vt,transitionProps:P,shadow:"sm",withinPortal:Se,portalProps:Fe,__staticSelector:"MultiSelect",onDirectionChange:Hr,switchDirectionOnFlip:Ae,zIndex:He,dropdownPosition:on,positionDependencies:[...Pt,Wr],classNames:h,styles:m,unstyled:xe,variant:D},F.createElement(hi.Target,null,F.createElement("div",{className:Xe.wrapper,role:"combobox","aria-haspopup":"listbox","aria-owns":Fn&&Vt?`${br}-items`:null,"aria-controls":br,"aria-expanded":Fn,onMouseLeave:()=>Ar(-1),tabIndex:-1},F.createElement("input",{type:"hidden",name:ct,value:me.join(","),form:Re,disabled:Y}),F.createElement(Pc,Hl({__staticSelector:"MultiSelect",style:{overflow:"hidden"},component:"div",multiline:!0,size:d,variant:D,disabled:Y,error:p,required:s,radius:ye,icon:ue,unstyled:xe,onMouseDown:$e=>{var yt;$e.preventDefault(),!Y&&!st.current&&Hn(!Fn),(yt=ln.current)==null||yt.focus()},classNames:U4(Hl({},h),{input:dt({[Xe.input]:!A},h==null?void 0:h.input)})},kE({theme:Lt,rightSection:X,rightSectionWidth:K,styles:m,size:d,shouldClear:q&&me.length>0,onClear:Jt,error:p,disabled:Y,clearButtonProps:qe,readOnly:zt})),F.createElement("div",{className:Xe.values,"data-clearable":q||void 0},Gt,F.createElement("input",Hl({ref:Ad(t,ln),type:"search",id:br,className:dt(Xe.searchInput,{[Xe.searchInputPointer]:!A,[Xe.searchInputInputHidden]:!Fn&&me.length>0||!A&&me.length>0,[Xe.searchInputEmpty]:me.length===0}),onKeyDown:Nt,value:Wr,onChange:ft,onFocus:xt,onBlur:Et,readOnly:!A||st.current||zt,placeholder:me.length===0?$:void 0,disabled:Y,"data-mantine-stop-propagation":Fn,autoComplete:"off",onCompositionStart:()=>$s(!0),onCompositionEnd:()=>$s(!1)},pn)))))),F.createElement(hi.Dropdown,{component:le||Nm,maxHeight:E,direction:Ro,id:br,innerRef:zs,__staticSelector:"MultiSelect",classNames:h,styles:m},F.createElement(py,{data:Be,hovered:Ce,classNames:h,styles:m,uuid:br,__staticSelector:"MultiSelect",onItemHover:Ar,onItemSelect:jt,itemsRefs:Fr,itemComponent:_,size:d,nothingFound:R,isItemSelected:Zt,creatable:U&&!!ee,createLabel:ee,unstyled:xe,variant:D}))))});jE.displayName="@mantine/core/MultiSelect";var aJ=Object.defineProperty,iJ=Object.defineProperties,lJ=Object.getOwnPropertyDescriptors,Bh=Object.getOwnPropertySymbols,IE=Object.prototype.hasOwnProperty,EE=Object.prototype.propertyIsEnumerable,q4=(e,t,n)=>t in e?aJ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Y0=(e,t)=>{for(var n in t||(t={}))IE.call(t,n)&&q4(e,n,t[n]);if(Bh)for(var n of Bh(t))EE.call(t,n)&&q4(e,n,t[n]);return e},cJ=(e,t)=>iJ(e,lJ(t)),uJ=(e,t)=>{var n={};for(var r in e)IE.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Bh)for(var r of Bh(e))t.indexOf(r)<0&&EE.call(e,r)&&(n[r]=e[r]);return n};const dJ={type:"text",size:"sm",__staticSelector:"TextInput"},OE=f.forwardRef((e,t)=>{const n=XI("TextInput",dJ,e),{inputProps:r,wrapperProps:o}=n,s=uJ(n,["inputProps","wrapperProps"]);return F.createElement(Pc.Wrapper,Y0({},o),F.createElement(Pc,cJ(Y0(Y0({},r),s),{ref:t})))});OE.displayName="@mantine/core/TextInput";function fJ({data:e,searchable:t,limit:n,searchValue:r,filter:o,value:s,filterDataOnExactSearchMatch:a}){if(!t)return e;const c=s!=null&&e.find(p=>p.value===s)||null;if(c&&!a&&(c==null?void 0:c.label)===r){if(n){if(n>=e.length)return e;const p=e.indexOf(c),h=p+n,m=h-e.length;return m>0?e.slice(p-m):e.slice(p,h)}return e}const d=[];for(let p=0;p=n));p+=1);return d}var pJ=so(()=>({input:{"&:not(:disabled)":{cursor:"pointer","&::selection":{backgroundColor:"transparent"}}}}));const hJ=pJ;var mJ=Object.defineProperty,gJ=Object.defineProperties,vJ=Object.getOwnPropertyDescriptors,Fh=Object.getOwnPropertySymbols,RE=Object.prototype.hasOwnProperty,ME=Object.prototype.propertyIsEnumerable,K4=(e,t,n)=>t in e?mJ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,vu=(e,t)=>{for(var n in t||(t={}))RE.call(t,n)&&K4(e,n,t[n]);if(Fh)for(var n of Fh(t))ME.call(t,n)&&K4(e,n,t[n]);return e},X0=(e,t)=>gJ(e,vJ(t)),bJ=(e,t)=>{var n={};for(var r in e)RE.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Fh)for(var r of Fh(e))t.indexOf(r)<0&&ME.call(e,r)&&(n[r]=e[r]);return n};function yJ(e,t){return t.label.toLowerCase().trim().includes(e.toLowerCase().trim())}function xJ(e,t){return!!e&&!t.some(n=>n.label.toLowerCase()===e.toLowerCase())}const wJ={required:!1,size:"sm",shadow:"sm",itemComponent:hy,transitionProps:{transition:"fade",duration:0},initiallyOpened:!1,filter:yJ,maxDropdownHeight:220,searchable:!1,clearable:!1,limit:1/0,disabled:!1,creatable:!1,shouldCreate:xJ,selectOnBlur:!1,switchDirectionOnFlip:!1,filterDataOnExactSearchMatch:!1,zIndex:uy("popover"),positionDependencies:[],dropdownPosition:"flip"},ky=f.forwardRef((e,t)=>{const n=XI("Select",wJ,e),{inputProps:r,wrapperProps:o,shadow:s,data:a,value:c,defaultValue:d,onChange:p,itemComponent:h,onKeyDown:m,onBlur:v,onFocus:b,transitionProps:w,initiallyOpened:y,unstyled:S,classNames:k,styles:_,filter:I,maxDropdownHeight:P,searchable:E,clearable:O,nothingFound:R,limit:M,disabled:T,onSearchChange:A,searchValue:$,rightSection:Q,rightSectionWidth:B,creatable:V,getCreateLabel:q,shouldCreate:G,selectOnBlur:D,onCreate:L,dropdownComponent:W,onDropdownClose:Y,onDropdownOpen:ae,withinPortal:ye,portalProps:ue,switchDirectionOnFlip:X,zIndex:K,name:U,dropdownPosition:se,allowDeselect:re,placeholder:oe,filterDataOnExactSearchMatch:pe,form:le,positionDependencies:ge,readOnly:_e,clearButtonProps:ie,hoverOnSearchChange:Se}=n,Fe=bJ(n,["inputProps","wrapperProps","shadow","data","value","defaultValue","onChange","itemComponent","onKeyDown","onBlur","onFocus","transitionProps","initiallyOpened","unstyled","classNames","styles","filter","maxDropdownHeight","searchable","clearable","nothingFound","limit","disabled","onSearchChange","searchValue","rightSection","rightSectionWidth","creatable","getCreateLabel","shouldCreate","selectOnBlur","onCreate","dropdownComponent","onDropdownClose","onDropdownOpen","withinPortal","portalProps","switchDirectionOnFlip","zIndex","name","dropdownPosition","allowDeselect","placeholder","filterDataOnExactSearchMatch","form","positionDependencies","readOnly","clearButtonProps","hoverOnSearchChange"]),{classes:Ae,cx:He,theme:Ct}=hJ(),[ct,on]=f.useState(y),[vt,bt]=f.useState(-1),we=f.useRef(),Re=f.useRef({}),[Pt,At]=f.useState("column"),xe=Pt==="column",{scrollIntoView:ht,targetRef:$t,scrollableRef:zt}=wj({duration:0,offset:5,cancelable:!1,isList:!0}),Ne=re===void 0?O:re,qe=ee=>{if(ct!==ee){on(ee);const he=ee?ae:Y;typeof he=="function"&&he()}},Pn=V&&typeof q=="function";let Pe=null;const Je=a.map(ee=>typeof ee=="string"?{label:ee,value:ee}:ee),Xe=uj({data:Je}),[dt,Lt,lr]=rd({value:c,defaultValue:d,finalValue:null,onChange:p}),pn=Xe.find(ee=>ee.value===dt),[ln,Fr]=rd({value:$,defaultValue:(pn==null?void 0:pn.label)||"",finalValue:void 0,onChange:A}),br=ee=>{Fr(ee),E&&typeof A=="function"&&A(ee)},Fn=()=>{var ee;_e||(Lt(null),lr||br(""),(ee=we.current)==null||ee.focus())};f.useEffect(()=>{const ee=Xe.find(he=>he.value===dt);ee?br(ee.label):(!Pn||!dt)&&br("")},[dt]),f.useEffect(()=>{pn&&(!E||!ct)&&br(pn.label)},[pn==null?void 0:pn.label]);const Hn=ee=>{if(!_e)if(Ne&&(pn==null?void 0:pn.value)===ee.value)Lt(null),qe(!1);else{if(ee.creatable&&typeof L=="function"){const he=L(ee.value);typeof he<"u"&&he!==null&&Lt(typeof he=="string"?he:he.value)}else Lt(ee.value);lr||br(ee.label),bt(-1),qe(!1),we.current.focus()}},Wn=fJ({data:Xe,searchable:E,limit:M,searchValue:ln,filter:I,filterDataOnExactSearchMatch:pe,value:dt});Pn&&G(ln,Wn)&&(Pe=q(ln),Wn.push({label:ln,value:ln,creatable:!0}));const Ar=(ee,he,ke)=>{let me=ee;for(;ke(me);)if(me=he(me),!Wn[me].disabled)return me;return ee};Ps(()=>{bt(Se&&ln?0:-1)},[ln,Se]);const Ro=dt?Wn.findIndex(ee=>ee.value===dt):0,Hr=!_e&&(Wn.length>0?ct:ct&&!!R),Wr=()=>{bt(ee=>{var he;const ke=Ar(ee,me=>me-1,me=>me>0);return $t.current=Re.current[(he=Wn[ke])==null?void 0:he.value],Hr&&ht({alignment:xe?"start":"end"}),ke})},fs=()=>{bt(ee=>{var he;const ke=Ar(ee,me=>me+1,me=>mewindow.setTimeout(()=>{var ee;$t.current=Re.current[(ee=Wn[Ro])==null?void 0:ee.value],ht({alignment:xe?"end":"start"})},50);Ps(()=>{Hr&&Nr()},[Hr]);const $s=ee=>{switch(typeof m=="function"&&m(ee),ee.key){case"ArrowUp":{ee.preventDefault(),ct?xe?Wr():fs():(bt(Ro),qe(!0),Nr());break}case"ArrowDown":{ee.preventDefault(),ct?xe?fs():Wr():(bt(Ro),qe(!0),Nr());break}case"Home":{if(!E){ee.preventDefault(),ct||qe(!0);const he=Wn.findIndex(ke=>!ke.disabled);bt(he),Hr&&ht({alignment:xe?"end":"start"})}break}case"End":{if(!E){ee.preventDefault(),ct||qe(!0);const he=Wn.map(ke=>!!ke.disabled).lastIndexOf(!1);bt(he),Hr&&ht({alignment:xe?"end":"start"})}break}case"Escape":{ee.preventDefault(),qe(!1),bt(-1);break}case" ":{E||(ee.preventDefault(),Wn[vt]&&ct?Hn(Wn[vt]):(qe(!0),bt(Ro),Nr()));break}case"Enter":E||ee.preventDefault(),Wn[vt]&&ct&&(ee.preventDefault(),Hn(Wn[vt]))}},ps=ee=>{typeof v=="function"&&v(ee);const he=Xe.find(ke=>ke.value===dt);D&&Wn[vt]&&ct&&Hn(Wn[vt]),br((he==null?void 0:he.label)||""),qe(!1)},ua=ee=>{typeof b=="function"&&b(ee),E&&qe(!0)},zs=ee=>{_e||(br(ee.currentTarget.value),O&&ee.currentTarget.value===""&&Lt(null),bt(-1),qe(!0))},J=()=>{_e||(qe(!ct),dt&&!ct&&bt(Ro))};return F.createElement(Pc.Wrapper,X0(vu({},o),{__staticSelector:"Select"}),F.createElement(hi,{opened:Hr,transitionProps:w,shadow:s,withinPortal:ye,portalProps:ue,__staticSelector:"Select",onDirectionChange:At,switchDirectionOnFlip:X,zIndex:K,dropdownPosition:se,positionDependencies:[...ge,ln],classNames:k,styles:_,unstyled:S,variant:r.variant},F.createElement(hi.Target,null,F.createElement("div",{role:"combobox","aria-haspopup":"listbox","aria-owns":Hr?`${r.id}-items`:null,"aria-controls":r.id,"aria-expanded":Hr,onMouseLeave:()=>bt(-1),tabIndex:-1},F.createElement("input",{type:"hidden",name:U,value:dt||"",form:le,disabled:T}),F.createElement(Pc,vu(X0(vu(vu({autoComplete:"off",type:"search"},r),Fe),{ref:Ad(t,we),onKeyDown:$s,__staticSelector:"Select",value:ln,placeholder:oe,onChange:zs,"aria-autocomplete":"list","aria-controls":Hr?`${r.id}-items`:null,"aria-activedescendant":vt>=0?`${r.id}-${vt}`:null,onMouseDown:J,onBlur:ps,onFocus:ua,readOnly:!E||_e,disabled:T,"data-mantine-stop-propagation":Hr,name:null,classNames:X0(vu({},k),{input:He({[Ae.input]:!E},k==null?void 0:k.input)})}),kE({theme:Ct,rightSection:Q,rightSectionWidth:B,styles:_,size:r.size,shouldClear:O&&!!pn,onClear:Fn,error:o.error,clearButtonProps:ie,disabled:T,readOnly:_e}))))),F.createElement(hi.Dropdown,{component:W||Nm,maxHeight:P,direction:Pt,id:r.id,innerRef:zt,__staticSelector:"Select",classNames:k,styles:_},F.createElement(py,{data:Wn,hovered:vt,classNames:k,styles:_,isItemSelected:ee=>ee===dt,uuid:r.id,__staticSelector:"Select",onItemHover:bt,onItemSelect:Hn,itemsRefs:Re,itemComponent:h,size:r.size,nothingFound:R,creatable:Pn&&!!Pe,createLabel:Pe,"aria-label":o.label,unstyled:S,variant:r.variant}))))});ky.displayName="@mantine/core/Select";const _y=()=>{const[e,t,n,r,o,s,a,c,d,p,h,m,v,b,w,y,S,k,_,I,P,E,O,R,M,T,A,$,Q,B,V,q,G,D,L,W,Y,ae]=Dc("colors",["base.50","base.100","base.150","base.200","base.250","base.300","base.350","base.400","base.450","base.500","base.550","base.600","base.650","base.700","base.750","base.800","base.850","base.900","base.950","accent.50","accent.100","accent.150","accent.200","accent.250","accent.300","accent.350","accent.400","accent.450","accent.500","accent.550","accent.600","accent.650","accent.700","accent.750","accent.800","accent.850","accent.900","accent.950"]);return{base50:e,base100:t,base150:n,base200:r,base250:o,base300:s,base350:a,base400:c,base450:d,base500:p,base550:h,base600:m,base650:v,base700:b,base750:w,base800:y,base850:S,base900:k,base950:_,accent50:I,accent100:P,accent150:E,accent200:O,accent250:R,accent300:M,accent350:T,accent400:A,accent450:$,accent500:Q,accent550:B,accent600:V,accent650:q,accent700:G,accent750:D,accent800:L,accent850:W,accent900:Y,accent950:ae}},DE=()=>{const{base50:e,base100:t,base200:n,base300:r,base400:o,base500:s,base600:a,base700:c,base800:d,base900:p,accent200:h,accent300:m,accent400:v,accent500:b,accent600:w}=_y(),{colorMode:y}=Ds(),[S]=Dc("shadows",["dark-lg"]);return f.useCallback(()=>({label:{color:ze(c,r)(y)},separatorLabel:{color:ze(s,s)(y),"::after":{borderTopColor:ze(r,c)(y)}},input:{backgroundColor:ze(e,p)(y),borderWidth:"2px",borderColor:ze(n,d)(y),color:ze(p,t)(y),paddingRight:24,fontWeight:600,"&:hover":{borderColor:ze(r,a)(y)},"&:focus":{borderColor:ze(m,w)(y)},"&:is(:focus, :hover)":{borderColor:ze(o,s)(y)},"&:focus-within":{borderColor:ze(h,w)(y)},"&[data-disabled]":{backgroundColor:ze(r,c)(y),color:ze(a,o)(y),cursor:"not-allowed"}},value:{backgroundColor:ze(t,p)(y),color:ze(p,t)(y),button:{color:ze(p,t)(y)},"&:hover":{backgroundColor:ze(r,c)(y),cursor:"pointer"}},dropdown:{backgroundColor:ze(n,d)(y),borderColor:ze(n,d)(y),boxShadow:S},item:{backgroundColor:ze(n,d)(y),color:ze(d,n)(y),padding:6,"&[data-hovered]":{color:ze(p,t)(y),backgroundColor:ze(r,c)(y)},"&[data-active]":{backgroundColor:ze(r,c)(y),"&:hover":{color:ze(p,t)(y),backgroundColor:ze(r,c)(y)}},"&[data-selected]":{backgroundColor:ze(v,w)(y),color:ze(e,t)(y),fontWeight:600,"&:hover":{backgroundColor:ze(b,b)(y),color:ze("white",e)(y)}},"&[data-disabled]":{color:ze(s,a)(y),cursor:"not-allowed"}},rightSection:{width:32,button:{color:ze(p,t)(y)}}}),[h,m,v,b,w,t,n,r,o,e,s,a,c,d,p,S,y])},SJ=e=>{const{searchable:t=!0,tooltip:n,inputRef:r,onChange:o,label:s,disabled:a,...c}=e,d=te(),[p,h]=f.useState(""),m=f.useCallback(y=>{y.shiftKey&&d(_o(!0))},[d]),v=f.useCallback(y=>{y.shiftKey||d(_o(!1))},[d]),b=f.useCallback(y=>{h(""),o&&o(y)},[o]),w=DE();return i.jsx(wn,{label:n,placement:"top",hasArrow:!0,children:i.jsx(ky,{ref:r,label:s?i.jsx(ho,{isDisabled:a,children:i.jsx(zo,{children:s})}):void 0,disabled:a,searchValue:p,onSearchChange:h,onChange:b,onKeyDown:m,onKeyUp:v,searchable:t,maxDropdownHeight:300,styles:w,...c})})},sr=f.memo(SJ),TE=f.forwardRef(({label:e,tooltip:t,description:n,disabled:r,...o},s)=>i.jsx(wn,{label:t,placement:"top",hasArrow:!0,openDelay:500,children:i.jsx(Oe,{ref:s,...o,children:i.jsxs(Oe,{children:[i.jsx(Sc,{children:e}),n&&i.jsx(Sc,{size:"xs",color:"base.600",children:n})]})})}));TE.displayName="IAIMantineSelectItemWithTooltip";const Oi=f.memo(TE),CJ=fe([Ye],({gallery:e})=>{const{autoAddBoardId:t}=e;return{autoAddBoardId:t}},Ge),kJ=()=>{const e=te(),{autoAddBoardId:t}=z(CJ),n=f.useRef(null),{boards:r,hasBoards:o}=Zh(void 0,{selectFromResult:({data:a})=>{const c=[{label:"None",value:"none"}];return a==null||a.forEach(({board_id:d,board_name:p})=>{c.push({label:p,value:d})}),{boards:c,hasBoards:c.length>1}}}),s=f.useCallback(a=>{a&&e(O_(a==="none"?void 0:a))},[e]);return i.jsx(sr,{label:"Auto-Add Board",inputRef:n,autoFocus:!0,placeholder:"Select a Board",value:t,data:r,nothingFound:"No matching Boards",itemComponent:Oi,disabled:!o,filter:(a,c)=>{var d;return((d=c.label)==null?void 0:d.toLowerCase().includes(a.toLowerCase().trim()))||c.value.toLowerCase().includes(a.toLowerCase().trim())},onChange:s})},_J=fe([Ye],e=>{const{galleryImageMinimumWidth:t,shouldAutoSwitch:n}=e.gallery;return{galleryImageMinimumWidth:t,shouldAutoSwitch:n}},Ge),PJ=()=>{const e=te(),{t}=be(),{galleryImageMinimumWidth:n,shouldAutoSwitch:r}=z(_J),o=s=>{e(Op(s))};return i.jsx(gl,{triggerComponent:i.jsx(Le,{tooltip:t("gallery.gallerySettings"),"aria-label":t("gallery.gallerySettings"),size:"sm",icon:i.jsx(Wb,{})}),children:i.jsxs(H,{direction:"column",gap:4,children:[i.jsx(_t,{value:n,onChange:o,min:32,max:256,hideTooltip:!0,label:t("gallery.galleryImageSize"),withReset:!0,handleReset:()=>e(Op(64))}),i.jsx(Gn,{label:t("gallery.autoSwitchNewImages"),isChecked:r,onChange:s=>e(FR(s.target.checked))}),i.jsx(kJ,{})]})})},jJ=e=>e.image?i.jsx(gm,{sx:{w:`${e.image.width}px`,h:"auto",objectFit:"contain",aspectRatio:`${e.image.width}/${e.image.height}`}}):i.jsx(H,{sx:{opacity:.7,w:"full",h:"full",alignItems:"center",justifyContent:"center",borderRadius:"base",bg:"base.200",_dark:{bg:"base.900"}},children:i.jsx(dl,{size:"xl"})}),mi=e=>{const{icon:t=al,boxSize:n=16}=e;return i.jsxs(H,{sx:{w:"full",h:"full",alignItems:"center",justifyContent:"center",borderRadius:"base",flexDir:"column",gap:2,userSelect:"none",opacity:.7,color:"base.700",_dark:{color:"base.500"},...e.sx},children:[i.jsx(Kr,{as:t,boxSize:n,opacity:.7}),e.label&&i.jsx(tt,{textAlign:"center",children:e.label})]})},Lm=0,Ri=1,Vc=2,AE=4;function IJ(e,t){return n=>e(t(n))}function EJ(e,t){return t(e)}function NE(e,t){return n=>e(t,n)}function Y4(e,t){return()=>e(t)}function Py(e,t){return t(e),e}function yl(...e){return e}function OJ(e){e()}function X4(e){return()=>e}function RJ(...e){return()=>{e.map(OJ)}}function Bm(){}function po(e,t){return e(Ri,t)}function Mr(e,t){e(Lm,t)}function jy(e){e(Vc)}function Fm(e){return e(AE)}function Un(e,t){return po(e,NE(t,Lm))}function Q4(e,t){const n=e(Ri,r=>{n(),t(r)});return n}function xr(){const e=[];return(t,n)=>{switch(t){case Vc:e.splice(0,e.length);return;case Ri:return e.push(n),()=>{const r=e.indexOf(n);r>-1&&e.splice(r,1)};case Lm:e.slice().forEach(r=>{r(n)});return;default:throw new Error(`unrecognized action ${t}`)}}}function qt(e){let t=e;const n=xr();return(r,o)=>{switch(r){case Ri:o(t);break;case Lm:t=o;break;case AE:return t}return n(r,o)}}function MJ(e){let t,n;const r=()=>t&&t();return function(o,s){switch(o){case Ri:return s?n===s?void 0:(r(),n=s,t=po(e,s),t):(r(),Bm);case Vc:r(),n=null;return;default:throw new Error(`unrecognized action ${o}`)}}}function $u(e){return Py(xr(),t=>Un(e,t))}function pc(e,t){return Py(qt(t),n=>Un(e,n))}function DJ(...e){return t=>e.reduceRight(EJ,t)}function Kt(e,...t){const n=DJ(...t);return(r,o)=>{switch(r){case Ri:return po(e,n(o));case Vc:jy(e);return}}}function $E(e,t){return e===t}function wo(e=$E){let t;return n=>r=>{e(t,r)||(t=r,n(r))}}function qr(e){return t=>n=>{e(n)&&t(n)}}function tr(e){return t=>IJ(t,e)}function ai(e){return t=>()=>t(e)}function fp(e,t){return n=>r=>n(t=e(t,r))}function m1(e){return t=>n=>{e>0?e--:t(n)}}function ju(e){let t=null,n;return r=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,r(t)},e))}}function J4(e){let t,n;return r=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{r(t)},e)}}function Ys(...e){const t=new Array(e.length);let n=0,r=null;const o=Math.pow(2,e.length)-1;return e.forEach((s,a)=>{const c=Math.pow(2,a);po(s,d=>{const p=n;n=n|c,t[a]=d,p!==o&&n===o&&r&&(r(),r=null)})}),s=>a=>{const c=()=>s([a].concat(t));n===o?c():r=c}}function Z4(...e){return function(t,n){switch(t){case Ri:return RJ(...e.map(r=>po(r,n)));case Vc:return;default:throw new Error(`unrecognized action ${t}`)}}}function xn(e,t=$E){return Kt(e,wo(t))}function wa(...e){const t=xr(),n=new Array(e.length);let r=0;const o=Math.pow(2,e.length)-1;return e.forEach((s,a)=>{const c=Math.pow(2,a);po(s,d=>{n[a]=d,r=r|c,r===o&&Mr(t,n)})}),function(s,a){switch(s){case Ri:return r===o&&a(n),po(t,a);case Vc:return jy(t);default:throw new Error(`unrecognized action ${s}`)}}}function ca(e,t=[],{singleton:n}={singleton:!0}){return{id:TJ(),constructor:e,dependencies:t,singleton:n}}const TJ=()=>Symbol();function AJ(e){const t=new Map,n=({id:r,constructor:o,dependencies:s,singleton:a})=>{if(a&&t.has(r))return t.get(r);const c=o(s.map(d=>n(d)));return a&&t.set(r,c),c};return n(e)}function NJ(e,t){const n={},r={};let o=0;const s=e.length;for(;o(S[k]=_=>{const I=y[t.methods[k]];Mr(I,_)},S),{})}function h(y){return a.reduce((S,k)=>(S[k]=MJ(y[t.events[k]]),S),{})}return{Component:F.forwardRef((y,S)=>{const{children:k,..._}=y,[I]=F.useState(()=>Py(AJ(e),E=>d(E,_))),[P]=F.useState(Y4(h,I));return pp(()=>{for(const E of a)E in _&&po(P[E],_[E]);return()=>{Object.values(P).map(jy)}},[_,P,I]),pp(()=>{d(I,_)}),F.useImperativeHandle(S,X4(p(I))),F.createElement(c.Provider,{value:I},n?F.createElement(n,NJ([...r,...o,...a],_),k):k)}),usePublisher:y=>F.useCallback(NE(Mr,F.useContext(c)[y]),[y]),useEmitterValue:y=>{const k=F.useContext(c)[y],[_,I]=F.useState(Y4(Fm,k));return pp(()=>po(k,P=>{P!==_&&I(X4(P))}),[k,_]),_},useEmitter:(y,S)=>{const _=F.useContext(c)[y];pp(()=>po(_,S),[S,_])}}}const zJ=typeof document<"u"?F.useLayoutEffect:F.useEffect,LJ=zJ;var Iy=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e))(Iy||{});const BJ={0:"debug",1:"log",2:"warn",3:"error"},FJ=()=>typeof globalThis>"u"?window:globalThis,zE=ca(()=>{const e=qt(3);return{log:qt((n,r,o=1)=>{var s;const a=(s=FJ().VIRTUOSO_LOG_LEVEL)!=null?s:Fm(e);o>=a&&console[BJ[o]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",n,r)}),logLevel:e}},[],{singleton:!0});function LE(e,t=!0){const n=F.useRef(null);let r=o=>{};if(typeof ResizeObserver<"u"){const o=F.useMemo(()=>new ResizeObserver(s=>{const a=s[0].target;a.offsetParent!==null&&e(a)}),[e]);r=s=>{s&&t?(o.observe(s),n.current=s):(n.current&&o.unobserve(n.current),n.current=null)}}return{ref:n,callbackRef:r}}function Hm(e,t=!0){return LE(e,t).callbackRef}function Hh(e,t){return Math.round(e.getBoundingClientRect()[t])}function BE(e,t){return Math.abs(e-t)<1.01}function FE(e,t,n,r=Bm,o){const s=F.useRef(null),a=F.useRef(null),c=F.useRef(null),d=F.useCallback(m=>{const v=m.target,b=v===window||v===document,w=b?window.pageYOffset||document.documentElement.scrollTop:v.scrollTop,y=b?document.documentElement.scrollHeight:v.scrollHeight,S=b?window.innerHeight:v.offsetHeight,k=()=>{e({scrollTop:Math.max(w,0),scrollHeight:y,viewportHeight:S})};m.suppressFlushSync?k():HR.flushSync(k),a.current!==null&&(w===a.current||w<=0||w===y-S)&&(a.current=null,t(!0),c.current&&(clearTimeout(c.current),c.current=null))},[e,t]);F.useEffect(()=>{const m=o||s.current;return r(o||s.current),d({target:m,suppressFlushSync:!0}),m.addEventListener("scroll",d,{passive:!0}),()=>{r(null),m.removeEventListener("scroll",d)}},[s,d,n,r,o]);function p(m){const v=s.current;if(!v||"offsetHeight"in v&&v.offsetHeight===0)return;const b=m.behavior==="smooth";let w,y,S;v===window?(y=Math.max(Hh(document.documentElement,"height"),document.documentElement.scrollHeight),w=window.innerHeight,S=document.documentElement.scrollTop):(y=v.scrollHeight,w=Hh(v,"height"),S=v.scrollTop);const k=y-w;if(m.top=Math.ceil(Math.max(Math.min(k,m.top),0)),BE(w,y)||m.top===S){e({scrollTop:S,scrollHeight:y,viewportHeight:w}),b&&t(!0);return}b?(a.current=m.top,c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{c.current=null,a.current=null,t(!0)},1e3)):a.current=null,v.scrollTo(m)}function h(m){s.current.scrollBy(m)}return{scrollerRef:s,scrollByCallback:h,scrollToCallback:p}}const Wm=ca(()=>{const e=xr(),t=xr(),n=qt(0),r=xr(),o=qt(0),s=xr(),a=xr(),c=qt(0),d=qt(0),p=qt(0),h=qt(0),m=xr(),v=xr(),b=qt(!1);return Un(Kt(e,tr(({scrollTop:w})=>w)),t),Un(Kt(e,tr(({scrollHeight:w})=>w)),a),Un(t,o),{scrollContainerState:e,scrollTop:t,viewportHeight:s,headerHeight:c,fixedHeaderHeight:d,fixedFooterHeight:p,footerHeight:h,scrollHeight:a,smoothScrollTargetReached:r,scrollTo:m,scrollBy:v,statefulScrollTop:o,deviation:n,scrollingInProgress:b}},[],{singleton:!0}),HJ=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function WJ(e){const t=typeof e=="number"?{index:e}:e;return t.align||(t.align="start"),(!t.behavior||!HJ)&&(t.behavior="auto"),t.offset||(t.offset=0),t}const Wh="up",zu="down",VJ="none",UJ={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollTop:0,viewportHeight:0,scrollHeight:0}},GJ=0,HE=ca(([{scrollContainerState:e,scrollTop:t,viewportHeight:n,headerHeight:r,footerHeight:o,scrollBy:s}])=>{const a=qt(!1),c=qt(!0),d=xr(),p=xr(),h=qt(4),m=qt(GJ),v=pc(Kt(Z4(Kt(xn(t),m1(1),ai(!0)),Kt(xn(t),m1(1),ai(!1),J4(100))),wo()),!1),b=pc(Kt(Z4(Kt(s,ai(!0)),Kt(s,ai(!1),J4(200))),wo()),!1);Un(Kt(wa(xn(t),xn(m)),tr(([_,I])=>_<=I),wo()),c),Un(Kt(c,ju(50)),p);const w=$u(Kt(wa(e,xn(n),xn(r),xn(o),xn(h)),fp((_,[{scrollTop:I,scrollHeight:P},E,O,R,M])=>{const T=I+E-P>-M,A={viewportHeight:E,scrollTop:I,scrollHeight:P};if(T){let Q,B;return I>_.state.scrollTop?(Q="SCROLLED_DOWN",B=_.state.scrollTop-I):(Q="SIZE_DECREASED",B=_.state.scrollTop-I||_.scrollTopDelta),{atBottom:!0,state:A,atBottomBecause:Q,scrollTopDelta:B}}let $;return A.scrollHeight>_.state.scrollHeight?$="SIZE_INCREASED":E<_.state.viewportHeight?$="VIEWPORT_HEIGHT_DECREASING":I<_.state.scrollTop?$="SCROLLING_UPWARDS":$="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:$,state:A}},UJ),wo((_,I)=>_&&_.atBottom===I.atBottom))),y=pc(Kt(e,fp((_,{scrollTop:I,scrollHeight:P,viewportHeight:E})=>{if(BE(_.scrollHeight,P))return{scrollTop:I,scrollHeight:P,jump:0,changed:!1};{const O=P-(I+E)<1;return _.scrollTop!==I&&O?{scrollHeight:P,scrollTop:I,jump:_.scrollTop-I,changed:!0}:{scrollHeight:P,scrollTop:I,jump:0,changed:!0}}},{scrollHeight:0,jump:0,scrollTop:0,changed:!1}),qr(_=>_.changed),tr(_=>_.jump)),0);Un(Kt(w,tr(_=>_.atBottom)),a),Un(Kt(a,ju(50)),d);const S=qt(zu);Un(Kt(e,tr(({scrollTop:_})=>_),wo(),fp((_,I)=>Fm(b)?{direction:_.direction,prevScrollTop:I}:{direction:I<_.prevScrollTop?Wh:zu,prevScrollTop:I},{direction:zu,prevScrollTop:0}),tr(_=>_.direction)),S),Un(Kt(e,ju(50),ai(VJ)),S);const k=qt(0);return Un(Kt(v,qr(_=>!_),ai(0)),k),Un(Kt(t,ju(100),Ys(v),qr(([_,I])=>!!I),fp(([_,I],[P])=>[I,P],[0,0]),tr(([_,I])=>I-_)),k),{isScrolling:v,isAtTop:c,isAtBottom:a,atBottomState:w,atTopStateChange:p,atBottomStateChange:d,scrollDirection:S,atBottomThreshold:h,atTopThreshold:m,scrollVelocity:k,lastJumpDueToItemResize:y}},yl(Wm)),qJ=ca(([{log:e}])=>{const t=qt(!1),n=$u(Kt(t,qr(r=>r),wo()));return po(t,r=>{r&&Fm(e)("props updated",{},Iy.DEBUG)}),{propsReady:t,didMount:n}},yl(zE),{singleton:!0});function WE(e,t){e==0?t():requestAnimationFrame(()=>WE(e-1,t))}function KJ(e,t){const n=t-1;return typeof e=="number"?e:e.index==="LAST"?n:e.index}function g1(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}function YJ(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}const Vh="top",Uh="bottom",ek="none";function tk(e,t,n){return typeof e=="number"?n===Wh&&t===Vh||n===zu&&t===Uh?e:0:n===Wh?t===Vh?e.main:e.reverse:t===Uh?e.main:e.reverse}function nk(e,t){return typeof e=="number"?e:e[t]||0}const XJ=ca(([{scrollTop:e,viewportHeight:t,deviation:n,headerHeight:r,fixedHeaderHeight:o}])=>{const s=xr(),a=qt(0),c=qt(0),d=qt(0),p=pc(Kt(wa(xn(e),xn(t),xn(r),xn(s,g1),xn(d),xn(a),xn(o),xn(n),xn(c)),tr(([h,m,v,[b,w],y,S,k,_,I])=>{const P=h-_,E=S+k,O=Math.max(v-P,0);let R=ek;const M=nk(I,Vh),T=nk(I,Uh);return b-=_,b+=v+k,w+=v+k,w-=_,b>h+E-M&&(R=Wh),wh!=null),wo(g1)),[0,0]);return{listBoundary:s,overscan:d,topListHeight:a,increaseViewportBy:c,visibleRange:p}},yl(Wm),{singleton:!0}),QJ=ca(([{scrollVelocity:e}])=>{const t=qt(!1),n=xr(),r=qt(!1);return Un(Kt(e,Ys(r,t,n),qr(([o,s])=>!!s),tr(([o,s,a,c])=>{const{exit:d,enter:p}=s;if(a){if(d(o,c))return!1}else if(p(o,c))return!0;return a}),wo()),t),po(Kt(wa(t,e,n),Ys(r)),([[o,s,a],c])=>o&&c&&c.change&&c.change(s,a)),{isSeeking:t,scrollSeekConfiguration:r,scrollVelocity:e,scrollSeekRangeChanged:n}},yl(HE),{singleton:!0});function JJ(e){let t=!1,n;return()=>(t||(t=!0,n=e()),n)}const ZJ=ca(([{scrollTo:e,scrollContainerState:t}])=>{const n=xr(),r=xr(),o=xr(),s=qt(!1),a=qt(void 0);return Un(Kt(wa(n,r),tr(([{viewportHeight:c,scrollTop:d,scrollHeight:p},{offsetTop:h}])=>({scrollTop:Math.max(0,d-h),scrollHeight:p,viewportHeight:c}))),t),Un(Kt(e,Ys(r),tr(([c,{offsetTop:d}])=>({...c,top:c.top+d}))),o),{useWindowScroll:s,customScrollParent:a,windowScrollContainerState:n,windowViewportRect:r,windowScrollTo:o}},yl(Wm)),Q0="-webkit-sticky",rk="sticky",VE=JJ(()=>{if(typeof document>"u")return rk;const e=document.createElement("div");return e.style.position=Q0,e.style.position===Q0?Q0:rk});function eZ(e,t){const n=F.useRef(null),r=F.useCallback(c=>{if(c===null||!c.offsetParent)return;const d=c.getBoundingClientRect(),p=d.width;let h,m;if(t){const v=t.getBoundingClientRect(),b=d.top-v.top;h=v.height-Math.max(0,b),m=b+t.scrollTop}else h=window.innerHeight-Math.max(0,d.top),m=d.top+window.pageYOffset;n.current={offsetTop:m,visibleHeight:h,visibleWidth:p},e(n.current)},[e,t]),{callbackRef:o,ref:s}=LE(r),a=F.useCallback(()=>{r(s.current)},[r,s]);return F.useEffect(()=>{if(t){t.addEventListener("scroll",a);const c=new ResizeObserver(a);return c.observe(t),()=>{t.removeEventListener("scroll",a),c.unobserve(t)}}else return window.addEventListener("scroll",a),window.addEventListener("resize",a),()=>{window.removeEventListener("scroll",a),window.removeEventListener("resize",a)}},[a,t]),o}F.createContext(void 0);const UE=F.createContext(void 0);function tZ(e){return e}VE();const nZ={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},GE={width:"100%",height:"100%",position:"absolute",top:0};VE();function el(e,t){if(typeof e!="string")return{context:t}}function rZ({usePublisher:e,useEmitter:t,useEmitterValue:n}){return F.memo(function({style:s,children:a,...c}){const d=e("scrollContainerState"),p=n("ScrollerComponent"),h=e("smoothScrollTargetReached"),m=n("scrollerRef"),v=n("context"),{scrollerRef:b,scrollByCallback:w,scrollToCallback:y}=FE(d,h,p,m);return t("scrollTo",y),t("scrollBy",w),F.createElement(p,{ref:b,style:{...nZ,...s},"data-test-id":"virtuoso-scroller","data-virtuoso-scroller":!0,tabIndex:0,...c,...el(p,v)},a)})}function oZ({usePublisher:e,useEmitter:t,useEmitterValue:n}){return F.memo(function({style:s,children:a,...c}){const d=e("windowScrollContainerState"),p=n("ScrollerComponent"),h=e("smoothScrollTargetReached"),m=n("totalListHeight"),v=n("deviation"),b=n("customScrollParent"),w=n("context"),{scrollerRef:y,scrollByCallback:S,scrollToCallback:k}=FE(d,h,p,Bm,b);return LJ(()=>(y.current=b||window,()=>{y.current=null}),[y,b]),t("windowScrollTo",k),t("scrollBy",S),F.createElement(p,{style:{position:"relative",...s,...m!==0?{height:m+v}:{}},"data-virtuoso-scroller":!0,...c,...el(p,w)},a)})}const ok={items:[],offsetBottom:0,offsetTop:0,top:0,bottom:0,itemHeight:0,itemWidth:0},sZ={items:[{index:0}],offsetBottom:0,offsetTop:0,top:0,bottom:0,itemHeight:0,itemWidth:0},{round:sk,ceil:ak,floor:Gh,min:J0,max:Lu}=Math;function aZ(e){return{...sZ,items:e}}function ik(e,t,n){return Array.from({length:t-e+1}).map((r,o)=>{const s=n===null?null:n[o+e];return{index:o+e,data:s}})}function iZ(e,t){return e&&e.column===t.column&&e.row===t.row}function hp(e,t){return e&&e.width===t.width&&e.height===t.height}const lZ=ca(([{overscan:e,visibleRange:t,listBoundary:n},{scrollTop:r,viewportHeight:o,scrollBy:s,scrollTo:a,smoothScrollTargetReached:c,scrollContainerState:d,footerHeight:p,headerHeight:h},m,v,{propsReady:b,didMount:w},{windowViewportRect:y,useWindowScroll:S,customScrollParent:k,windowScrollContainerState:_,windowScrollTo:I},P])=>{const E=qt(0),O=qt(0),R=qt(ok),M=qt({height:0,width:0}),T=qt({height:0,width:0}),A=xr(),$=xr(),Q=qt(0),B=qt(null),V=qt({row:0,column:0}),q=xr(),G=xr(),D=qt(!1),L=qt(0),W=qt(!0),Y=qt(!1);po(Kt(w,Ys(L),qr(([U,se])=>!!se)),()=>{Mr(W,!1),Mr(O,0)}),po(Kt(wa(w,W,T,M,L,Y),qr(([U,se,re,oe,,pe])=>U&&!se&&re.height!==0&&oe.height!==0&&!pe)),([,,,,U])=>{Mr(Y,!0),WE(1,()=>{Mr(A,U)}),Q4(Kt(r),()=>{Mr(n,[0,0]),Mr(W,!0)})}),Un(Kt(G,qr(U=>U!=null&&U.scrollTop>0),ai(0)),O),po(Kt(w,Ys(G),qr(([,U])=>U!=null)),([,U])=>{U&&(Mr(M,U.viewport),Mr(T,U==null?void 0:U.item),Mr(V,U.gap),U.scrollTop>0&&(Mr(D,!0),Q4(Kt(r,m1(1)),se=>{Mr(D,!1)}),Mr(a,{top:U.scrollTop})))}),Un(Kt(M,tr(({height:U})=>U)),o),Un(Kt(wa(xn(M,hp),xn(T,hp),xn(V,(U,se)=>U&&U.column===se.column&&U.row===se.row),xn(r)),tr(([U,se,re,oe])=>({viewport:U,item:se,gap:re,scrollTop:oe}))),q),Un(Kt(wa(xn(E),t,xn(V,iZ),xn(T,hp),xn(M,hp),xn(B),xn(O),xn(D),xn(W),xn(L)),qr(([,,,,,,,U])=>!U),tr(([U,[se,re],oe,pe,le,ge,_e,,ie,Se])=>{const{row:Fe,column:Ae}=oe,{height:He,width:Ct}=pe,{width:ct}=le;if(_e===0&&(U===0||ct===0))return ok;if(Ct===0){const $t=KJ(Se,U),zt=$t===0?Math.max(_e-1,0):$t;return aZ(ik($t,zt,ge))}const on=qE(ct,Ct,Ae);let vt,bt;ie?se===0&&re===0&&_e>0?(vt=0,bt=_e-1):(vt=on*Gh((se+Fe)/(He+Fe)),bt=on*ak((re+Fe)/(He+Fe))-1,bt=J0(U-1,Lu(bt,on-1)),vt=J0(bt,Lu(0,vt))):(vt=0,bt=-1);const we=ik(vt,bt,ge),{top:Re,bottom:Pt}=lk(le,oe,pe,we),At=ak(U/on),ht=At*He+(At-1)*Fe-Pt;return{items:we,offsetTop:Re,offsetBottom:ht,top:Re,bottom:Pt,itemHeight:He,itemWidth:Ct}})),R),Un(Kt(B,qr(U=>U!==null),tr(U=>U.length)),E),Un(Kt(wa(M,T,R,V),qr(([U,se,{items:re}])=>re.length>0&&se.height!==0&&U.height!==0),tr(([U,se,{items:re},oe])=>{const{top:pe,bottom:le}=lk(U,oe,se,re);return[pe,le]}),wo(g1)),n);const ae=qt(!1);Un(Kt(r,Ys(ae),tr(([U,se])=>se||U!==0)),ae);const ye=$u(Kt(xn(R),qr(({items:U})=>U.length>0),Ys(E,ae),qr(([{items:U},se,re])=>re&&U[U.length-1].index===se-1),tr(([,U])=>U-1),wo())),ue=$u(Kt(xn(R),qr(({items:U})=>U.length>0&&U[0].index===0),ai(0),wo())),X=$u(Kt(xn(R),Ys(D),qr(([{items:U},se])=>U.length>0&&!se),tr(([{items:U}])=>({startIndex:U[0].index,endIndex:U[U.length-1].index})),wo(YJ),ju(0)));Un(X,v.scrollSeekRangeChanged),Un(Kt(A,Ys(M,T,E,V),tr(([U,se,re,oe,pe])=>{const le=WJ(U),{align:ge,behavior:_e,offset:ie}=le;let Se=le.index;Se==="LAST"&&(Se=oe-1),Se=Lu(0,Se,J0(oe-1,Se));let Fe=v1(se,pe,re,Se);return ge==="end"?Fe=sk(Fe-se.height+re.height):ge==="center"&&(Fe=sk(Fe-se.height/2+re.height/2)),ie&&(Fe+=ie),{top:Fe,behavior:_e}})),a);const K=pc(Kt(R,tr(U=>U.offsetBottom+U.bottom)),0);return Un(Kt(y,tr(U=>({width:U.visibleWidth,height:U.visibleHeight}))),M),{data:B,totalCount:E,viewportDimensions:M,itemDimensions:T,scrollTop:r,scrollHeight:$,overscan:e,scrollBy:s,scrollTo:a,scrollToIndex:A,smoothScrollTargetReached:c,windowViewportRect:y,windowScrollTo:I,useWindowScroll:S,customScrollParent:k,windowScrollContainerState:_,deviation:Q,scrollContainerState:d,footerHeight:p,headerHeight:h,initialItemCount:O,gap:V,restoreStateFrom:G,...v,initialTopMostItemIndex:L,gridState:R,totalListHeight:K,...m,startReached:ue,endReached:ye,rangeChanged:X,stateChanged:q,propsReady:b,stateRestoreInProgress:D,...P}},yl(XJ,Wm,HE,QJ,qJ,ZJ,zE));function lk(e,t,n,r){const{height:o}=n;if(o===void 0||r.length===0)return{top:0,bottom:0};const s=v1(e,t,n,r[0].index),a=v1(e,t,n,r[r.length-1].index)+o;return{top:s,bottom:a}}function v1(e,t,n,r){const o=qE(e.width,n.width,t.column),s=Gh(r/o),a=s*n.height+Lu(0,s-1)*t.row;return a>0?a+t.row:a}function qE(e,t,n){return Lu(1,Gh((e+n)/(Gh(t)+n)))}const cZ=ca(()=>{const e=qt(p=>`Item ${p}`),t=qt({}),n=qt(null),r=qt("virtuoso-grid-item"),o=qt("virtuoso-grid-list"),s=qt(tZ),a=qt("div"),c=qt(Bm),d=(p,h=null)=>pc(Kt(t,tr(m=>m[p]),wo()),h);return{context:n,itemContent:e,components:t,computeItemKey:s,itemClassName:r,listClassName:o,headerFooterTag:a,scrollerRef:c,FooterComponent:d("Footer"),HeaderComponent:d("Header"),ListComponent:d("List","div"),ItemComponent:d("Item","div"),ScrollerComponent:d("Scroller","div"),ScrollSeekPlaceholder:d("ScrollSeekPlaceholder","div")}}),uZ=ca(([e,t])=>({...e,...t}),yl(lZ,cZ)),dZ=F.memo(function(){const t=fr("gridState"),n=fr("listClassName"),r=fr("itemClassName"),o=fr("itemContent"),s=fr("computeItemKey"),a=fr("isSeeking"),c=Is("scrollHeight"),d=fr("ItemComponent"),p=fr("ListComponent"),h=fr("ScrollSeekPlaceholder"),m=fr("context"),v=Is("itemDimensions"),b=Is("gap"),w=fr("log"),y=fr("stateRestoreInProgress"),S=Hm(k=>{const _=k.parentElement.parentElement.scrollHeight;c(_);const I=k.firstChild;if(I){const{width:P,height:E}=I.getBoundingClientRect();v({width:P,height:E})}b({row:ck("row-gap",getComputedStyle(k).rowGap,w),column:ck("column-gap",getComputedStyle(k).columnGap,w)})});return y?null:F.createElement(p,{ref:S,className:n,...el(p,m),style:{paddingTop:t.offsetTop,paddingBottom:t.offsetBottom},"data-test-id":"virtuoso-item-list"},t.items.map(k=>{const _=s(k.index,k.data,m);return a?F.createElement(h,{key:_,...el(h,m),index:k.index,height:t.itemHeight,width:t.itemWidth}):F.createElement(d,{...el(d,m),className:r,"data-index":k.index,key:_},o(k.index,k.data,m))}))}),fZ=F.memo(function(){const t=fr("HeaderComponent"),n=Is("headerHeight"),r=fr("headerFooterTag"),o=Hm(a=>n(Hh(a,"height"))),s=fr("context");return t?F.createElement(r,{ref:o},F.createElement(t,el(t,s))):null}),pZ=F.memo(function(){const t=fr("FooterComponent"),n=Is("footerHeight"),r=fr("headerFooterTag"),o=Hm(a=>n(Hh(a,"height"))),s=fr("context");return t?F.createElement(r,{ref:o},F.createElement(t,el(t,s))):null}),hZ=({children:e})=>{const t=F.useContext(UE),n=Is("itemDimensions"),r=Is("viewportDimensions"),o=Hm(s=>{r(s.getBoundingClientRect())});return F.useEffect(()=>{t&&(r({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,r,n]),F.createElement("div",{style:GE,ref:o},e)},mZ=({children:e})=>{const t=F.useContext(UE),n=Is("windowViewportRect"),r=Is("itemDimensions"),o=fr("customScrollParent"),s=eZ(n,o);return F.useEffect(()=>{t&&(r({height:t.itemHeight,width:t.itemWidth}),n({offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,r]),F.createElement("div",{ref:s,style:GE},e)},gZ=F.memo(function({...t}){const n=fr("useWindowScroll"),r=fr("customScrollParent"),o=r||n?yZ:bZ,s=r||n?mZ:hZ;return F.createElement(o,{...t},F.createElement(s,null,F.createElement(fZ,null),F.createElement(dZ,null),F.createElement(pZ,null)))}),{Component:vZ,usePublisher:Is,useEmitterValue:fr,useEmitter:KE}=$J(uZ,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged"}},gZ),bZ=rZ({usePublisher:Is,useEmitterValue:fr,useEmitter:KE}),yZ=oZ({usePublisher:Is,useEmitterValue:fr,useEmitter:KE});function ck(e,t,n){return t!=="normal"&&!(t!=null&&t.endsWith("px"))&&n(`${e} was not resolved to pixel value correctly`,t,Iy.WARN),t==="normal"?0:parseInt(t??"0",10)}const YE=vZ,xZ=({imageDTO:e})=>i.jsx(H,{sx:{pointerEvents:"none",flexDirection:"column",position:"absolute",top:0,insetInlineStart:0,p:2,alignItems:"flex-start",gap:2},children:i.jsxs(pl,{variant:"solid",colorScheme:"base",children:[e.width," × ",e.height]})}),Vm=({postUploadAction:e,isDisabled:t})=>{const n=z(d=>d.gallery.autoAddBoardId),[r]=j_(),o=f.useCallback(d=>{const p=d[0];p&&r({file:p,image_category:"user",is_intermediate:!1,postUploadAction:e??{type:"TOAST"},board_id:n})},[n,e,r]),{getRootProps:s,getInputProps:a,open:c}=zb({accept:{"image/png":[".png"],"image/jpeg":[".jpg",".jpeg",".png"]},onDropAccepted:o,disabled:t,noDrag:!0,multiple:!1});return{getUploadButtonProps:s,getUploadInputProps:a,openUploader:c}},Ey=()=>{const e=te(),t=Bc(),{t:n}=be(),r=f.useCallback(()=>{t({title:n("toast.parameterSet"),status:"info",duration:2500,isClosable:!0})},[n,t]),o=f.useCallback(()=>{t({title:n("toast.parameterNotSet"),status:"warning",duration:2500,isClosable:!0})},[n,t]),s=f.useCallback(()=>{t({title:n("toast.parametersSet"),status:"info",duration:2500,isClosable:!0})},[n,t]),a=f.useCallback(()=>{t({title:n("toast.parametersNotSet"),status:"warning",duration:2500,isClosable:!0})},[n,t]),c=f.useCallback((P,E)=>{if(If(P)||Ef(E)){If(P)&&e(Ru(P)),Ef(E)&&e(Mu(E)),r();return}o()},[e,r,o]),d=f.useCallback(P=>{if(!If(P)){o();return}e(Ru(P)),r()},[e,r,o]),p=f.useCallback(P=>{if(!Ef(P)){o();return}e(Mu(P)),r()},[e,r,o]),h=f.useCallback(P=>{if(!R2(P)){o();return}e(Rp(P)),r()},[e,r,o]),m=f.useCallback(P=>{if(!M2(P)){o();return}e(Mp(P)),r()},[e,r,o]),v=f.useCallback(P=>{if(!D2(P)){o();return}e(hv(P)),r()},[e,r,o]),b=f.useCallback(P=>{if(!T2(P)){o();return}e(mv(P)),r()},[e,r,o]),w=f.useCallback(P=>{if(!A2(P)){o();return}e(Dp(P)),r()},[e,r,o]),y=f.useCallback(P=>{if(!N2(P)){o();return}e(hc(P)),r()},[e,r,o]),S=f.useCallback(P=>{if(!$2(P)){o();return}e(mc(P)),r()},[e,r,o]),k=f.useCallback(P=>{if(!z2(P)){o();return}e(Tp(P)),r()},[e,r,o]),_=f.useCallback(P=>{e($1(P))},[e]),I=f.useCallback(P=>{if(!P){a();return}const{cfg_scale:E,height:O,model:R,positive_prompt:M,negative_prompt:T,scheduler:A,seed:$,steps:Q,width:B,strength:V}=P;M2(E)&&e(Mp(E)),D2(R)&&e(hv(R)),If(M)&&e(Ru(M)),Ef(T)&&e(Mu(T)),T2(A)&&e(mv(A)),R2($)&&e(Rp($)),A2(Q)&&e(Dp(Q)),N2(B)&&e(hc(B)),$2(O)&&e(mc(O)),z2(V)&&e(Tp(V)),s()},[a,s,e]);return{recallBothPrompts:c,recallPositivePrompt:d,recallNegativePrompt:p,recallSeed:h,recallCfgScale:m,recallModel:v,recallScheduler:b,recallSteps:w,recallWidth:y,recallHeight:S,recallStrength:k,recallAllParameters:I,sendToImageToImage:_}},ar=e=>{const t=z(a=>a.config.disabledTabs),n=z(a=>a.config.disabledFeatures),r=z(a=>a.config.disabledSDFeatures),o=f.useMemo(()=>n.includes(e)||r.includes(e)||t.includes(e),[n,r,t,e]),s=f.useMemo(()=>!(n.includes(e)||r.includes(e)||t.includes(e)),[n,r,t,e]);return{isFeatureDisabled:o,isFeatureEnabled:s}},Oy=()=>{const e=Bc(),{t}=be(),n=f.useMemo(()=>!!navigator.clipboard&&!!window.ClipboardItem,[]),r=f.useCallback(async o=>{n||e({title:t("toast.problemCopyingImage"),description:"Your browser doesn't support the Clipboard API.",status:"error",duration:2500,isClosable:!0});try{const a=await(await fetch(o)).blob();await navigator.clipboard.write([new ClipboardItem({[a.type]:a})]),e({title:t("toast.imageCopied"),status:"success",duration:2500,isClosable:!0})}catch(s){e({title:t("toast.problemCopyingImage"),description:String(s),status:"error",duration:2500,isClosable:!0})}},[n,t,e]);return{isClipboardAPIAvailable:n,copyImageToClipboard:r}};function wZ(e,t,n){var r=this,o=f.useRef(null),s=f.useRef(0),a=f.useRef(null),c=f.useRef([]),d=f.useRef(),p=f.useRef(),h=f.useRef(e),m=f.useRef(!0);f.useEffect(function(){h.current=e},[e]);var v=!t&&t!==0&&typeof window<"u";if(typeof e!="function")throw new TypeError("Expected a function");t=+t||0;var b=!!(n=n||{}).leading,w=!("trailing"in n)||!!n.trailing,y="maxWait"in n,S=y?Math.max(+n.maxWait||0,t):null;f.useEffect(function(){return m.current=!0,function(){m.current=!1}},[]);var k=f.useMemo(function(){var _=function(M){var T=c.current,A=d.current;return c.current=d.current=null,s.current=M,p.current=h.current.apply(A,T)},I=function(M,T){v&&cancelAnimationFrame(a.current),a.current=v?requestAnimationFrame(M):setTimeout(M,T)},P=function(M){if(!m.current)return!1;var T=M-o.current;return!o.current||T>=t||T<0||y&&M-s.current>=S},E=function(M){return a.current=null,w&&c.current?_(M):(c.current=d.current=null,p.current)},O=function M(){var T=Date.now();if(P(T))return E(T);if(m.current){var A=t-(T-o.current),$=y?Math.min(A,S-(T-s.current)):A;I(M,$)}},R=function(){var M=Date.now(),T=P(M);if(c.current=[].slice.call(arguments),d.current=r,o.current=M,T){if(!a.current&&m.current)return s.current=o.current,I(O,t),b?_(o.current):p.current;if(y)return I(O,t),_(o.current)}return a.current||I(O,t),p.current};return R.cancel=function(){a.current&&(v?cancelAnimationFrame(a.current):clearTimeout(a.current)),s.current=0,c.current=o.current=d.current=a.current=null},R.isPending=function(){return!!a.current},R.flush=function(){return a.current?E(Date.now()):p.current},R},[b,y,t,S,w,v]);return k}function SZ(e,t){return e===t}function uk(e){return typeof e=="function"?function(){return e}:e}function Ry(e,t,n){var r,o,s=n&&n.equalityFn||SZ,a=(r=f.useState(uk(e)),o=r[1],[r[0],f.useCallback(function(m){return o(uk(m))},[])]),c=a[0],d=a[1],p=wZ(f.useCallback(function(m){return d(m)},[d]),t,n),h=f.useRef(e);return s(h.current,e)||(p(e),h.current=e),[c,p]}z1("gallery/requestedBoardImagesDeletion");const CZ=z1("gallery/sentImageToCanvas"),XE=z1("gallery/sentImageToImg2Img"),kZ=e=>{const{imageDTO:t}=e,n=f.useMemo(()=>fe([Ye],({gallery:V})=>({isInBatch:V.batchImageNames.includes(t.image_name)}),Ge),[t.image_name]),{isInBatch:r}=z(n),o=te(),{t:s}=be(),a=Bc(),c=ar("unifiedCanvas").isFeatureEnabled,d=ar("batches").isFeatureEnabled,{onClickAddToBoard:p}=f.useContext(T_),[h,m]=Ry(t.image_name,500),{currentData:v}=L1(m.isPending()?oo.skipToken:h??oo.skipToken),{isClipboardAPIAvailable:b,copyImageToClipboard:w}=Oy(),y=v==null?void 0:v.metadata,S=f.useCallback(()=>{t&&o(B1(t))},[o,t]),{recallBothPrompts:k,recallSeed:_,recallAllParameters:I}=Ey(),[P]=WR(),E=f.useCallback(()=>{k(y==null?void 0:y.positive_prompt,y==null?void 0:y.negative_prompt)},[y==null?void 0:y.negative_prompt,y==null?void 0:y.positive_prompt,k]),O=f.useCallback(()=>{_(y==null?void 0:y.seed)},[y==null?void 0:y.seed,_]),R=f.useCallback(()=>{o(XE()),o($1(t))},[o,t]),M=f.useCallback(()=>{o(CZ()),o(VR(t)),o(em()),o(ql("unifiedCanvas")),a({title:s("toast.sentToUnifiedCanvas"),status:"success",duration:2500,isClosable:!0})},[o,t,s,a]),T=f.useCallback(()=>{console.log(y),I(y)},[y,I]),A=f.useCallback(()=>{p(t)},[t,p]),$=f.useCallback(()=>{t.board_id&&P({imageDTO:t})},[t,P]),Q=f.useCallback(()=>{o(UR([t.image_name]))},[o,t.image_name]),B=f.useCallback(()=>{w(t.image_url)},[w,t.image_url]);return i.jsxs(i.Fragment,{children:[i.jsx(_r,{as:"a",href:t.image_url,target:"_blank",icon:i.jsx(XH,{}),children:s("common.openInNewTab")}),b&&i.jsx(_r,{icon:i.jsx(Fc,{}),onClickCapture:B,children:s("parameters.copyImage")}),i.jsx(_r,{as:"a",download:!0,href:t.image_url,target:"_blank",icon:i.jsx(Bb,{}),w:"100%",children:s("parameters.downloadImage")}),i.jsx(_r,{icon:i.jsx(x6,{}),onClickCapture:E,isDisabled:(y==null?void 0:y.positive_prompt)===void 0&&(y==null?void 0:y.negative_prompt)===void 0,children:s("parameters.usePrompt")}),i.jsx(_r,{icon:i.jsx(w6,{}),onClickCapture:O,isDisabled:(y==null?void 0:y.seed)===void 0,children:s("parameters.useSeed")}),i.jsx(_r,{icon:i.jsx(d6,{}),onClickCapture:T,isDisabled:!y,children:s("parameters.useAll")}),i.jsx(_r,{icon:i.jsx(CS,{}),onClickCapture:R,id:"send-to-img2img",children:s("parameters.sendToImg2Img")}),c&&i.jsx(_r,{icon:i.jsx(CS,{}),onClickCapture:M,id:"send-to-canvas",children:s("parameters.sendToUnifiedCanvas")}),d&&i.jsx(_r,{icon:i.jsx(M0,{}),isDisabled:r,onClickCapture:Q,children:"Add to Batch"}),i.jsx(_r,{icon:i.jsx(M0,{}),onClickCapture:A,children:t.board_id?"Change Board":"Add to Board"}),t.board_id&&i.jsx(_r,{icon:i.jsx(M0,{}),onClickCapture:$,children:"Remove from Board"}),i.jsx(_r,{sx:{color:"error.600",_dark:{color:"error.300"}},icon:i.jsx(us,{}),onClickCapture:S,children:s("gallery.deleteImage")})]})},QE=f.memo(kZ),_Z=({imageDTO:e,children:t})=>{const n=f.useCallback(r=>{r.preventDefault()},[]);return i.jsx(oj,{menuProps:{size:"sm",isLazy:!0},menuButtonProps:{bg:"transparent",_hover:{bg:"transparent"}},renderMenu:()=>e?i.jsx(zc,{sx:{visibility:"visible !important"},motionProps:nm,onContextMenu:n,children:i.jsx(QE,{imageDTO:e})}):null,children:t})},JE=f.memo(_Z),PZ=e=>{const{data:t,disabled:n,onClick:r}=e,o=f.useRef(ui()),{attributes:s,listeners:a,setNodeRef:c}=GR({id:o.current,disabled:n,data:t});return i.jsx(Oe,{onClick:r,ref:c,position:"absolute",w:"full",h:"full",top:0,insetInlineStart:0,...s,...a})},jZ=f.memo(PZ),IZ=e=>{const{imageDTO:t,onClickReset:n,onError:r,onClick:o,withResetIcon:s=!1,withMetadataOverlay:a=!1,isDropDisabled:c=!1,isDragDisabled:d=!1,isUploadDisabled:p=!1,minSize:h=24,postUploadAction:m,imageSx:v,fitContainer:b=!1,droppableData:w,draggableData:y,dropLabel:S,isSelected:k=!1,thumbnail:_=!1,resetTooltip:I="Reset",resetIcon:P=i.jsx(Hb,{}),noContentFallback:E=i.jsx(mi,{icon:al}),useThumbailFallback:O,withHoverOverlay:R=!1}=e,{colorMode:M}=Ds(),[T,A]=f.useState(!1),$=f.useCallback(()=>{A(!0)},[]),Q=f.useCallback(()=>{A(!1)},[]),{getUploadButtonProps:B,getUploadInputProps:V}=Vm({postUploadAction:m,isDisabled:p}),q=vp("drop-shadow(0px 0px 0.1rem var(--invokeai-colors-base-600))","drop-shadow(0px 0px 0.1rem var(--invokeai-colors-base-800))"),G=p?{}:{cursor:"pointer",bg:ze("base.200","base.800")(M),_hover:{bg:ze("base.300","base.650")(M),color:ze("base.500","base.300")(M)}};return i.jsx(JE,{imageDTO:t,children:D=>i.jsxs(H,{ref:D,onMouseOver:$,onMouseOut:Q,sx:{width:"full",height:"full",alignItems:"center",justifyContent:"center",position:"relative",minW:h||void 0,minH:h||void 0,userSelect:"none",cursor:d||!t?"default":"pointer"},children:[t&&i.jsxs(H,{sx:{w:"full",h:"full",position:b?"absolute":"relative",alignItems:"center",justifyContent:"center"},children:[i.jsx(Tc,{src:_?t.thumbnail_url:t.image_url,fallbackStrategy:"beforeLoadOrError",fallbackSrc:O?t.thumbnail_url:void 0,fallback:O?void 0:i.jsx(jJ,{image:t}),width:t.width,height:t.height,onError:r,draggable:!1,sx:{objectFit:"contain",maxW:"full",maxH:"full",borderRadius:"base",...v}}),a&&i.jsx(xZ,{imageDTO:t}),i.jsx(ly,{isSelected:k,isHovered:R?T:!1})]}),!t&&!p&&i.jsx(i.Fragment,{children:i.jsxs(H,{sx:{minH:h,w:"full",h:"full",alignItems:"center",justifyContent:"center",borderRadius:"base",transitionProperty:"common",transitionDuration:"0.1s",color:ze("base.500","base.500")(M),...G},...B(),children:[i.jsx("input",{...V()}),i.jsx(Kr,{as:Md,sx:{boxSize:16}})]})}),!t&&p&&E,t&&!d&&i.jsx(jZ,{data:y,disabled:d||!t,onClick:o}),!c&&i.jsx(iy,{data:w,disabled:c,dropLabel:S}),n&&s&&t&&i.jsx(Le,{onClick:n,"aria-label":I,tooltip:I,icon:P,size:"sm",variant:"link",sx:{position:"absolute",top:1,insetInlineEnd:1,p:0,minW:0,svg:{transitionProperty:"common",transitionDuration:"normal",fill:"base.100",_hover:{fill:"base.50"},filter:q}}})]})})},yi=f.memo(IZ),EZ=()=>i.jsx(Oe,{sx:{position:"relative",height:"full",width:"full","::before":{content:"''",display:"block",pt:"100%"}},children:i.jsx(H,{sx:{position:"absolute",top:0,insetInlineStart:0,height:"full",width:"full",alignItems:"center",justifyContent:"center",borderRadius:"base",bg:"base.100",color:"base.500",_dark:{color:"base.700",bg:"base.850"}},children:i.jsx(Kr,{as:qH,boxSize:16,opacity:.7})})}),ZE=()=>i.jsx(gm,{sx:{position:"relative",height:"full",width:"full","::before":{content:"''",display:"block",pt:"100%"}},children:i.jsx(Oe,{sx:{position:"absolute",top:0,insetInlineStart:0,height:"full",width:"full"}})}),OZ=e=>fe([Ye],t=>({selectionCount:t.gallery.selection.length,selection:t.gallery.selection,isSelected:t.gallery.selection.includes(e)}),Ge),RZ=e=>{const t=te(),{imageName:n}=e,{currentData:r,isLoading:o,isError:s}=os(n),a=f.useMemo(()=>OZ(n),[n]),{isSelected:c,selectionCount:d,selection:p}=z(a),h=f.useCallback(()=>{t(qR([n]))},[t,n]),m=f.useMemo(()=>{if(d>1)return{id:"batch",payloadType:"IMAGE_NAMES",payload:{image_names:p}};if(r)return{id:"batch",payloadType:"IMAGE_DTO",payload:{imageDTO:r}}},[r,p,d]);return o?i.jsx(ZE,{}):s||!r?i.jsx(EZ,{}):i.jsx(Oe,{sx:{w:"full",h:"full",touchAction:"none"},children:i.jsx(JE,{imageDTO:r,children:v=>i.jsx(Oe,{position:"relative",userSelect:"none",ref:v,sx:{display:"flex",justifyContent:"center",alignItems:"center",aspectRatio:"1/1"},children:i.jsx(yi,{imageDTO:r,draggableData:m,isSelected:c,minSize:0,onClickReset:h,isDropDisabled:!0,imageSx:{w:"full",h:"full"},isUploadDisabled:!0,resetTooltip:"Remove from batch",withResetIcon:!0,thumbnail:!0})},n)})})},MZ=f.memo(RZ),eO=Te((e,t)=>i.jsx(Oe,{className:"item-container",ref:t,p:1.5,children:e.children})),tO=Te((e,t)=>{const n=z(r=>r.gallery.galleryImageMinimumWidth);return i.jsx(rl,{...e,className:"list-container",ref:t,sx:{gridTemplateColumns:`repeat(auto-fill, minmax(${n}px, 1fr));`},children:e.children})}),DZ=fe([Ye],e=>({imageNames:e.gallery.batchImageNames}),Ge),TZ=()=>{const{t:e}=be(),t=f.useRef(null),[n,r]=f.useState(null),[o,s]=sy({defer:!0,options:{scrollbars:{visibility:"auto",autoHide:"leave",autoHideDelay:1300,theme:"os-theme-dark"},overflow:{x:"hidden"}}}),{imageNames:a}=z(DZ);return f.useEffect(()=>{const{current:c}=t;return n&&c&&o({target:c,elements:{viewport:n}}),()=>{var d;return(d=s())==null?void 0:d.destroy()}},[n,o,s]),a.length?i.jsx(Oe,{ref:t,"data-overlayscrollbars":"",h:"100%",children:i.jsx(YE,{style:{height:"100%"},data:a,components:{Item:eO,List:tO},scrollerRef:r,itemContent:(c,d)=>i.jsx(MZ,{imageName:d},d)})}):i.jsx(mi,{label:e("gallery.noImagesInGallery"),icon:al})},AZ=f.memo(TZ),NZ=e=>{const t=z(s=>s.gallery.galleryView),{data:n}=KR(e),{data:r}=YR(e),o=f.useMemo(()=>t==="images"?n:r,[t,r,n]);return{totalImages:n,totalAssets:r,currentViewTotal:o}},$Z=e=>fe([Ye],({gallery:t})=>({isSelected:t.selection.includes(e),selectionCount:t.selection.length,selection:t.selection}),Ge),zZ=e=>{const t=te(),{imageName:n}=e,{currentData:r}=os(n),o=f.useMemo(()=>$Z(n),[n]),{isSelected:s,selectionCount:a,selection:c}=z(o),d=f.useCallback(()=>{t(gv(n))},[t,n]),p=f.useCallback(m=>{m.stopPropagation(),r&&t(B1(r))},[t,r]),h=f.useMemo(()=>{if(a>1)return{id:"gallery-image",payloadType:"IMAGE_NAMES",payload:{image_names:c}};if(r)return{id:"gallery-image",payloadType:"IMAGE_DTO",payload:{imageDTO:r}}},[r,c,a]);return r?i.jsx(Oe,{sx:{w:"full",h:"full",touchAction:"none"},children:i.jsx(H,{userSelect:"none",sx:{position:"relative",justifyContent:"center",alignItems:"center",aspectRatio:"1/1"},children:i.jsx(yi,{onClick:d,imageDTO:r,draggableData:h,isSelected:s,minSize:0,onClickReset:p,imageSx:{w:"full",h:"full"},isDropDisabled:!0,isUploadDisabled:!0,thumbnail:!0,withHoverOverlay:!0})})}):i.jsx(ZE,{})},LZ=f.memo(zZ),BZ={defer:!0,options:{scrollbars:{visibility:"auto",autoHide:"leave",autoHideDelay:1300,theme:"os-theme-dark"},overflow:{x:"hidden"}}},FZ=()=>{const{t:e}=be(),t=f.useRef(null),[n,r]=f.useState(null),[o,s]=sy(BZ),a=z(S=>S.gallery.selectedBoardId),{currentViewTotal:c}=NZ(a),d=z(A_),{currentData:p,isFetching:h,isSuccess:m,isError:v}=XR(d),[b]=N_(),w=f.useMemo(()=>!p||!c?!1:p.ids.length{w&&b({...d,offset:(p==null?void 0:p.ids.length)??0,limit:$_})},[w,b,d,p==null?void 0:p.ids.length]);return f.useEffect(()=>{const{current:S}=t;return n&&S&&o({target:S,elements:{viewport:n}}),()=>{var k;return(k=s())==null?void 0:k.destroy()}},[n,o,s]),p?m&&(p==null?void 0:p.ids.length)===0?i.jsx(H,{sx:{w:"full",h:"full",alignItems:"center",justifyContent:"center"},children:i.jsx(mi,{label:e("gallery.noImagesInGallery"),icon:al})}):m&&p?i.jsxs(i.Fragment,{children:[i.jsx(Oe,{ref:t,"data-overlayscrollbars":"",h:"100%",children:i.jsx(YE,{style:{height:"100%"},data:p.ids,endReached:y,components:{Item:eO,List:tO},scrollerRef:r,itemContent:(S,k)=>i.jsx(LZ,{imageName:k},k)})}),i.jsx(rn,{onClick:y,isDisabled:!w,isLoading:h,loadingText:"Loading",flexShrink:0,children:`Load More (${p.ids.length} of ${c})`})]}):v?i.jsx(Oe,{sx:{w:"full",h:"full"},children:i.jsx(mi,{label:"Unable to load Gallery",icon:h6})}):null:i.jsx(H,{sx:{w:"full",h:"full",alignItems:"center",justifyContent:"center"},children:i.jsx(mi,{label:"Loading...",icon:al})})},HZ=f.memo(FZ),WZ=fe([Ye],e=>{const{selectedBoardId:t,galleryView:n}=e.gallery;return{selectedBoardId:t,galleryView:n}},Ge),VZ=()=>{const e=f.useRef(null),t=f.useRef(null),{selectedBoardId:n,galleryView:r}=z(WZ),o=te(),{isOpen:s,onToggle:a}=ss(),c=f.useCallback(()=>{o(L2("images"))},[o]),d=f.useCallback(()=>{o(L2("assets"))},[o]);return i.jsxs(VP,{sx:{flexDirection:"column",h:"full",w:"full",borderRadius:"base"},children:[i.jsxs(Oe,{sx:{w:"full"},children:[i.jsxs(H,{ref:e,sx:{alignItems:"center",justifyContent:"space-between",gap:2},children:[i.jsx(iU,{isOpen:s,onToggle:a}),i.jsx(PJ,{}),i.jsx(cU,{})]}),i.jsx(Oe,{children:i.jsx(oU,{isOpen:s})})]}),i.jsxs(H,{ref:t,direction:"column",gap:2,h:"full",w:"full",children:[i.jsx(H,{sx:{alignItems:"center",justifyContent:"space-between",gap:2},children:i.jsx(Ed,{index:r==="images"?0:1,variant:"unstyled",size:"sm",sx:{w:"full"},children:i.jsx(Od,{children:i.jsxs(nr,{isAttached:!0,sx:{w:"full"},children:[i.jsx(wc,{as:rn,size:"sm",isChecked:r==="images",onClick:c,sx:{w:"full"},leftIcon:i.jsx(tW,{}),children:"Images"}),i.jsx(wc,{as:rn,size:"sm",isChecked:r==="assets",onClick:d,sx:{w:"full"},leftIcon:i.jsx(fW,{}),children:"Assets"})]})})})}),n==="batch"?i.jsx(AZ,{}):i.jsx(HZ,{})]})]})},nO=f.memo(VZ),UZ=fe([Kn,La,QR,ir],(e,t,n,r)=>{const{shouldPinGallery:o,shouldShowGallery:s}=t,{galleryImageMinimumWidth:a}=n;return{activeTabName:e,isStaging:r,shouldPinGallery:o,shouldShowGallery:s,galleryImageMinimumWidth:a,isResizable:e!=="unifiedCanvas"}},{memoizeOptions:{resultEqualityCheck:Qt}}),GZ=()=>{const e=te(),{shouldPinGallery:t,shouldShowGallery:n,galleryImageMinimumWidth:r}=z(UZ),o=()=>{e(vv(!1)),t&&e(So())};nt("esc",()=>{e(vv(!1))},{enabled:()=>!t,preventDefault:!0},[t]);const s=32;return nt("shift+up",()=>{if(r<256){const a=Es(r+s,32,256);e(Op(a))}},[r]),nt("shift+down",()=>{if(r>32){const a=Es(r-s,32,256);e(Op(a))}},[r]),t?null:i.jsx(i6,{direction:"right",isResizable:!0,isOpen:n,onClose:o,minWidth:400,children:i.jsx(nO,{})})},qZ=f.memo(GZ),KZ=e=>{const{label:t,isDisabled:n=!1,width:r="auto",formControlProps:o,formLabelProps:s,tooltip:a,...c}=e;return i.jsx(wn,{label:a,hasArrow:!0,placement:"top",isDisabled:!a,children:i.jsxs(ho,{isDisabled:n,width:r,display:"flex",alignItems:"center",...o,children:[t&&i.jsx(zo,{my:1,flexGrow:1,sx:{cursor:n?"not-allowed":"pointer",...s==null?void 0:s.sx,pe:4},...s,children:t}),i.jsx(Nb,{...c})]})})},wr=f.memo(KZ),YZ=fe([Ye,JR],({system:e,config:t,imageDeletion:n},r)=>{const{shouldConfirmOnDelete:o}=e,{canRestoreDeletedImagesFromBin:s}=t,{imageToDelete:a,isModalOpen:c}=n;return{shouldConfirmOnDelete:o,canRestoreDeletedImagesFromBin:s,imageToDelete:a,imageUsage:r,isModalOpen:c}},Ge),XZ=()=>{const e=te(),{t}=be(),{shouldConfirmOnDelete:n,canRestoreDeletedImagesFromBin:r,imageToDelete:o,imageUsage:s,isModalOpen:a}=z(YZ),c=f.useCallback(m=>e(z_(!m.target.checked)),[e]),d=f.useCallback(()=>{e(B2()),e(ZR(!1))},[e]),p=f.useCallback(()=>{!o||!s||(e(B2()),e(eM({imageDTO:o,imageUsage:s})))},[e,o,s]),h=f.useRef(null);return i.jsx(Pd,{isOpen:a,onClose:d,leastDestructiveRef:h,isCentered:!0,children:i.jsx(Ma,{children:i.jsxs(jd,{children:[i.jsx(Ra,{fontSize:"lg",fontWeight:"bold",children:t("gallery.deleteImage")}),i.jsx(Da,{children:i.jsxs(H,{direction:"column",gap:3,children:[i.jsx(ej,{imageUsage:s}),i.jsx(hl,{}),i.jsx(tt,{children:t(r?"gallery.deleteImageBin":"gallery.deleteImagePermanent")}),i.jsx(tt,{children:t("common.areYouSure")}),i.jsx(wr,{label:t("common.dontAskMeAgain"),isChecked:!n,onChange:c})]})}),i.jsxs(Oa,{children:[i.jsx(rn,{ref:h,onClick:d,children:"Cancel"}),i.jsx(rn,{colorScheme:"error",onClick:p,ml:3,children:"Delete"})]})]})})})},QZ=f.memo(XZ);function JZ(e){const{title:t,hotkey:n,description:r}=e;return i.jsxs(rl,{sx:{gridTemplateColumns:"auto max-content",justifyContent:"space-between",alignItems:"center"},children:[i.jsxs(rl,{children:[i.jsx(tt,{fontWeight:600,children:t}),r&&i.jsx(tt,{sx:{fontSize:"sm"},variant:"subtext",children:r})]}),i.jsx(Oe,{sx:{fontSize:"sm",fontWeight:600,px:2,py:1},children:n})]})}function ZZ({children:e}){const{isOpen:t,onOpen:n,onClose:r}=ss(),{t:o}=be(),s=[{title:o("hotkeys.invoke.title"),desc:o("hotkeys.invoke.desc"),hotkey:"Ctrl+Enter"},{title:o("hotkeys.cancel.title"),desc:o("hotkeys.cancel.desc"),hotkey:"Shift+X"},{title:o("hotkeys.focusPrompt.title"),desc:o("hotkeys.focusPrompt.desc"),hotkey:"Alt+A"},{title:o("hotkeys.toggleOptions.title"),desc:o("hotkeys.toggleOptions.desc"),hotkey:"O"},{title:o("hotkeys.pinOptions.title"),desc:o("hotkeys.pinOptions.desc"),hotkey:"Shift+O"},{title:o("hotkeys.toggleGallery.title"),desc:o("hotkeys.toggleGallery.desc"),hotkey:"G"},{title:o("hotkeys.maximizeWorkSpace.title"),desc:o("hotkeys.maximizeWorkSpace.desc"),hotkey:"F"},{title:o("hotkeys.changeTabs.title"),desc:o("hotkeys.changeTabs.desc"),hotkey:"1-5"}],a=[{title:o("hotkeys.setPrompt.title"),desc:o("hotkeys.setPrompt.desc"),hotkey:"P"},{title:o("hotkeys.setSeed.title"),desc:o("hotkeys.setSeed.desc"),hotkey:"S"},{title:o("hotkeys.setParameters.title"),desc:o("hotkeys.setParameters.desc"),hotkey:"A"},{title:o("hotkeys.upscale.title"),desc:o("hotkeys.upscale.desc"),hotkey:"Shift+U"},{title:o("hotkeys.showInfo.title"),desc:o("hotkeys.showInfo.desc"),hotkey:"I"},{title:o("hotkeys.sendToImageToImage.title"),desc:o("hotkeys.sendToImageToImage.desc"),hotkey:"Shift+I"},{title:o("hotkeys.deleteImage.title"),desc:o("hotkeys.deleteImage.desc"),hotkey:"Del"},{title:o("hotkeys.closePanels.title"),desc:o("hotkeys.closePanels.desc"),hotkey:"Esc"}],c=[{title:o("hotkeys.previousImage.title"),desc:o("hotkeys.previousImage.desc"),hotkey:"Arrow Left"},{title:o("hotkeys.nextImage.title"),desc:o("hotkeys.nextImage.desc"),hotkey:"Arrow Right"},{title:o("hotkeys.toggleGalleryPin.title"),desc:o("hotkeys.toggleGalleryPin.desc"),hotkey:"Shift+G"},{title:o("hotkeys.increaseGalleryThumbSize.title"),desc:o("hotkeys.increaseGalleryThumbSize.desc"),hotkey:"Shift+Up"},{title:o("hotkeys.decreaseGalleryThumbSize.title"),desc:o("hotkeys.decreaseGalleryThumbSize.desc"),hotkey:"Shift+Down"}],d=[{title:o("hotkeys.selectBrush.title"),desc:o("hotkeys.selectBrush.desc"),hotkey:"B"},{title:o("hotkeys.selectEraser.title"),desc:o("hotkeys.selectEraser.desc"),hotkey:"E"},{title:o("hotkeys.decreaseBrushSize.title"),desc:o("hotkeys.decreaseBrushSize.desc"),hotkey:"["},{title:o("hotkeys.increaseBrushSize.title"),desc:o("hotkeys.increaseBrushSize.desc"),hotkey:"]"},{title:o("hotkeys.decreaseBrushOpacity.title"),desc:o("hotkeys.decreaseBrushOpacity.desc"),hotkey:"Shift + ["},{title:o("hotkeys.increaseBrushOpacity.title"),desc:o("hotkeys.increaseBrushOpacity.desc"),hotkey:"Shift + ]"},{title:o("hotkeys.moveTool.title"),desc:o("hotkeys.moveTool.desc"),hotkey:"V"},{title:o("hotkeys.fillBoundingBox.title"),desc:o("hotkeys.fillBoundingBox.desc"),hotkey:"Shift + F"},{title:o("hotkeys.eraseBoundingBox.title"),desc:o("hotkeys.eraseBoundingBox.desc"),hotkey:"Delete / Backspace"},{title:o("hotkeys.colorPicker.title"),desc:o("hotkeys.colorPicker.desc"),hotkey:"C"},{title:o("hotkeys.toggleSnap.title"),desc:o("hotkeys.toggleSnap.desc"),hotkey:"N"},{title:o("hotkeys.quickToggleMove.title"),desc:o("hotkeys.quickToggleMove.desc"),hotkey:"Hold Space"},{title:o("hotkeys.toggleLayer.title"),desc:o("hotkeys.toggleLayer.desc"),hotkey:"Q"},{title:o("hotkeys.clearMask.title"),desc:o("hotkeys.clearMask.desc"),hotkey:"Shift+C"},{title:o("hotkeys.hideMask.title"),desc:o("hotkeys.hideMask.desc"),hotkey:"H"},{title:o("hotkeys.showHideBoundingBox.title"),desc:o("hotkeys.showHideBoundingBox.desc"),hotkey:"Shift+H"},{title:o("hotkeys.mergeVisible.title"),desc:o("hotkeys.mergeVisible.desc"),hotkey:"Shift+M"},{title:o("hotkeys.saveToGallery.title"),desc:o("hotkeys.saveToGallery.desc"),hotkey:"Shift+S"},{title:o("hotkeys.copyToClipboard.title"),desc:o("hotkeys.copyToClipboard.desc"),hotkey:"Ctrl+C"},{title:o("hotkeys.downloadImage.title"),desc:o("hotkeys.downloadImage.desc"),hotkey:"Shift+D"},{title:o("hotkeys.undoStroke.title"),desc:o("hotkeys.undoStroke.desc"),hotkey:"Ctrl+Z"},{title:o("hotkeys.redoStroke.title"),desc:o("hotkeys.redoStroke.desc"),hotkey:"Ctrl+Shift+Z, Ctrl+Y"},{title:o("hotkeys.resetView.title"),desc:o("hotkeys.resetView.desc"),hotkey:"R"},{title:o("hotkeys.previousStagingImage.title"),desc:o("hotkeys.previousStagingImage.desc"),hotkey:"Arrow Left"},{title:o("hotkeys.nextStagingImage.title"),desc:o("hotkeys.nextStagingImage.desc"),hotkey:"Arrow Right"},{title:o("hotkeys.acceptStagingImage.title"),desc:o("hotkeys.acceptStagingImage.desc"),hotkey:"Enter"}],p=h=>i.jsx(H,{flexDir:"column",gap:4,children:h.map((m,v)=>i.jsxs(H,{flexDir:"column",px:2,gap:4,children:[i.jsx(JZ,{title:m.title,description:m.desc,hotkey:m.hotkey}),v{const{data:t}=tM(),n=f.useRef(null),r=rO(n);return i.jsxs(H,{alignItems:"center",gap:3,ps:1,ref:n,children:[i.jsx(Tc,{src:M_,alt:"invoke-ai-logo",sx:{w:"32px",h:"32px",minW:"32px",minH:"32px",userSelect:"none"}}),i.jsxs(H,{sx:{gap:3,alignItems:"center"},children:[i.jsxs(tt,{sx:{fontSize:"xl",userSelect:"none"},children:["invoke ",i.jsx("strong",{children:"ai"})]}),i.jsx(Fo,{children:e&&r&&t&&i.jsx(Xr.div,{initial:{opacity:0},animate:{opacity:1,transition:{duration:.15}},exit:{opacity:0,transition:{delay:.8}},children:i.jsx(tt,{sx:{fontWeight:600,marginTop:1,color:"base.300",fontSize:14},variant:"subtext",children:t.version})},"statusText")})]})]})},aee=e=>{const{tooltip:t,inputRef:n,label:r,disabled:o,required:s,...a}=e,c=DE();return i.jsx(wn,{label:t,placement:"top",hasArrow:!0,children:i.jsx(ky,{label:r?i.jsx(ho,{isRequired:s,isDisabled:o,children:i.jsx(zo,{children:r})}):void 0,disabled:o,ref:n,styles:c,...a})})},Yr=f.memo(aee);function Yo(e){const{t}=be(),{label:n,textProps:r,useBadge:o=!1,badgeLabel:s=t("settings.experimental"),badgeProps:a,...c}=e;return i.jsxs(H,{justifyContent:"space-between",py:1,children:[i.jsxs(H,{gap:2,alignItems:"center",children:[i.jsx(tt,{sx:{fontSize:14,_dark:{color:"base.300"}},...r,children:n}),o&&i.jsx(pl,{size:"xs",sx:{px:2,color:"base.700",bg:"accent.200",_dark:{bg:"accent.500",color:"base.200"}},...a,children:s})]}),i.jsx(wr,{...c})]})}const Gl=e=>i.jsx(H,{sx:{flexDirection:"column",gap:2,p:4,borderRadius:"base",bg:"base.100",_dark:{bg:"base.900"}},children:e.children});function iee(){const e=te(),{data:t,refetch:n}=nM(),[r,{isLoading:o}]=rM(),s=f.useCallback(()=>{r().unwrap().then(c=>{e(oM()),e(F1()),e(Dn({title:`Cleared ${c} intermediates`,status:"info"}))})},[r,e]);f.useEffect(()=>{n()},[n]);const a=t?`Clear ${t} Intermediate${t>1?"s":""}`:"No Intermediates to Clear";return i.jsxs(Gl,{children:[i.jsx(Xs,{size:"sm",children:"Clear Intermediates"}),i.jsx(rn,{colorScheme:"warning",onClick:s,isLoading:o,isDisabled:!t,children:a}),i.jsx(tt,{fontWeight:"bold",children:"Clearing intermediates will reset your Canvas and ControlNet state."}),i.jsx(tt,{variant:"subtext",children:"Intermediate images are byproducts of generation, different from the result images in the gallery. Clearing intermediates will free disk space."}),i.jsx(tt,{variant:"subtext",children:"Your gallery images will not be deleted."})]})}const lee=()=>{const{base50:e,base100:t,base200:n,base300:r,base400:o,base500:s,base600:a,base700:c,base800:d,base900:p,accent200:h,accent300:m,accent400:v,accent500:b,accent600:w}=_y(),{colorMode:y}=Ds(),[S]=Dc("shadows",["dark-lg"]);return f.useCallback(()=>({label:{color:ze(c,r)(y)},separatorLabel:{color:ze(s,s)(y),"::after":{borderTopColor:ze(r,c)(y)}},searchInput:{":placeholder":{color:ze(r,c)(y)}},input:{backgroundColor:ze(e,p)(y),borderWidth:"2px",borderColor:ze(n,d)(y),color:ze(p,t)(y),paddingRight:24,fontWeight:600,"&:hover":{borderColor:ze(r,a)(y)},"&:focus":{borderColor:ze(m,w)(y)},"&:is(:focus, :hover)":{borderColor:ze(o,s)(y)},"&:focus-within":{borderColor:ze(h,w)(y)},"&[data-disabled]":{backgroundColor:ze(r,c)(y),color:ze(a,o)(y),cursor:"not-allowed"}},value:{backgroundColor:ze(n,d)(y),color:ze(p,t)(y),button:{color:ze(p,t)(y)},"&:hover":{backgroundColor:ze(r,c)(y),cursor:"pointer"}},dropdown:{backgroundColor:ze(n,d)(y),borderColor:ze(n,d)(y),boxShadow:S},item:{backgroundColor:ze(n,d)(y),color:ze(d,n)(y),padding:6,"&[data-hovered]":{color:ze(p,t)(y),backgroundColor:ze(r,c)(y)},"&[data-active]":{backgroundColor:ze(r,c)(y),"&:hover":{color:ze(p,t)(y),backgroundColor:ze(r,c)(y)}},"&[data-selected]":{backgroundColor:ze(v,w)(y),color:ze(e,t)(y),fontWeight:600,"&:hover":{backgroundColor:ze(b,b)(y),color:ze("white",e)(y)}},"&[data-disabled]":{color:ze(s,a)(y),cursor:"not-allowed"}},rightSection:{width:24,padding:20,button:{color:ze(p,t)(y)}}}),[h,m,v,b,w,t,n,r,o,e,s,a,c,d,p,S,y])},cee=e=>{const{searchable:t=!0,tooltip:n,inputRef:r,label:o,disabled:s,...a}=e,c=te(),d=f.useCallback(m=>{m.shiftKey&&c(_o(!0))},[c]),p=f.useCallback(m=>{m.shiftKey||c(_o(!1))},[c]),h=lee();return i.jsx(wn,{label:n,placement:"top",hasArrow:!0,isOpen:!0,children:i.jsx(jE,{label:o?i.jsx(ho,{isDisabled:s,children:i.jsx(zo,{children:o})}):void 0,ref:r,disabled:s,onKeyDown:d,onKeyUp:p,searchable:t,maxDropdownHeight:300,styles:h,...a})})},uee=f.memo(cee),dee=cs(H1,(e,t)=>({value:t,label:e})).sort((e,t)=>e.label.localeCompare(t.label));function fee(){const e=te(),{t}=be(),n=z(o=>o.ui.favoriteSchedulers),r=f.useCallback(o=>{e(sM(o))},[e]);return i.jsx(uee,{label:t("settings.favoriteSchedulers"),value:n,data:dee,onChange:r,clearable:!0,searchable:!0,maxSelectedValues:99,placeholder:t("settings.favoriteSchedulersPlaceholder")})}const pee={ar:Ln.t("common.langArabic",{lng:"ar"}),nl:Ln.t("common.langDutch",{lng:"nl"}),en:Ln.t("common.langEnglish",{lng:"en"}),fr:Ln.t("common.langFrench",{lng:"fr"}),de:Ln.t("common.langGerman",{lng:"de"}),he:Ln.t("common.langHebrew",{lng:"he"}),it:Ln.t("common.langItalian",{lng:"it"}),ja:Ln.t("common.langJapanese",{lng:"ja"}),ko:Ln.t("common.langKorean",{lng:"ko"}),pl:Ln.t("common.langPolish",{lng:"pl"}),pt_BR:Ln.t("common.langBrPortuguese",{lng:"pt_BR"}),pt:Ln.t("common.langPortuguese",{lng:"pt"}),ru:Ln.t("common.langRussian",{lng:"ru"}),zh_CN:Ln.t("common.langSimplifiedChinese",{lng:"zh_CN"}),es:Ln.t("common.langSpanish",{lng:"es"}),uk:Ln.t("common.langUkranian",{lng:"ua"})},hee=fe([Ye],({system:e,ui:t,generation:n})=>{const{shouldConfirmOnDelete:r,enableImageDebugging:o,consoleLogLevel:s,shouldLogToConsole:a,shouldAntialiasProgressImage:c,isNodesEnabled:d,shouldUseNSFWChecker:p,shouldUseWatermarker:h}=e,{shouldUseCanvasBetaLayout:m,shouldUseSliders:v,shouldShowProgressInViewer:b}=t,{shouldShowAdvancedOptions:w}=n;return{shouldConfirmOnDelete:r,enableImageDebugging:o,shouldUseCanvasBetaLayout:m,shouldUseSliders:v,shouldShowProgressInViewer:b,consoleLogLevel:s,shouldLogToConsole:a,shouldAntialiasProgressImage:c,shouldShowAdvancedOptions:w,isNodesEnabled:d,shouldUseNSFWChecker:p,shouldUseWatermarker:h}},{memoizeOptions:{resultEqualityCheck:Qt}}),mee=({children:e,config:t})=>{const n=te(),{t:r}=be(),o=(t==null?void 0:t.shouldShowBetaLayout)??!0,s=(t==null?void 0:t.shouldShowDeveloperSettings)??!0,a=(t==null?void 0:t.shouldShowResetWebUiText)??!0,c=(t==null?void 0:t.shouldShowAdvancedOptionsSettings)??!0,d=(t==null?void 0:t.shouldShowClearIntermediates)??!0,p=(t==null?void 0:t.shouldShowNodesToggle)??!0,h=(t==null?void 0:t.shouldShowLocalizationToggle)??!0;f.useEffect(()=>{s||n(F2(!1))},[s,n]);const{isNSFWCheckerAvailable:m,isWatermarkerAvailable:v}=L_(void 0,{selectFromResult:({data:X})=>({isNSFWCheckerAvailable:(X==null?void 0:X.nsfw_methods.includes("nsfw_checker"))??!1,isWatermarkerAvailable:(X==null?void 0:X.watermarking_methods.includes("invisible_watermark"))??!1})}),{isOpen:b,onOpen:w,onClose:y}=ss(),{isOpen:S,onOpen:k,onClose:_}=ss(),{shouldConfirmOnDelete:I,enableImageDebugging:P,shouldUseCanvasBetaLayout:E,shouldUseSliders:O,shouldShowProgressInViewer:R,consoleLogLevel:M,shouldLogToConsole:T,shouldAntialiasProgressImage:A,shouldShowAdvancedOptions:$,isNodesEnabled:Q,shouldUseNSFWChecker:B,shouldUseWatermarker:V}=z(hee),q=f.useCallback(()=>{Object.keys(window.localStorage).forEach(X=>{(aM.includes(X)||X.startsWith(iM))&&localStorage.removeItem(X)}),y(),k()},[y,k]),G=f.useCallback(X=>{n(lM(X))},[n]),D=f.useCallback(X=>{n(cM(X))},[n]),L=f.useCallback(X=>{n(F2(X.target.checked))},[n]),W=f.useCallback(X=>{n(uM(X.target.checked))},[n]),{colorMode:Y,toggleColorMode:ae}=Ds(),ye=ar("localization").isFeatureEnabled,ue=z(V5);return i.jsxs(i.Fragment,{children:[f.cloneElement(e,{onClick:w}),i.jsxs(Qu,{isOpen:b,onClose:y,size:"2xl",isCentered:!0,children:[i.jsx(Ma,{}),i.jsxs(Ju,{children:[i.jsx(Ra,{bg:"none",children:r("common.settingsLabel")}),i.jsx(Ob,{}),i.jsx(Da,{children:i.jsxs(H,{sx:{gap:4,flexDirection:"column"},children:[i.jsxs(Gl,{children:[i.jsx(Xs,{size:"sm",children:r("settings.general")}),i.jsx(Yo,{label:r("settings.confirmOnDelete"),isChecked:I,onChange:X=>n(z_(X.target.checked))}),c&&i.jsx(Yo,{label:r("settings.showAdvancedOptions"),isChecked:$,onChange:X=>n(dM(X.target.checked))})]}),i.jsxs(Gl,{children:[i.jsx(Xs,{size:"sm",children:r("settings.generation")}),i.jsx(fee,{}),i.jsx(Yo,{label:"Enable NSFW Checker",isDisabled:!m,isChecked:B,onChange:X=>n(fM(X.target.checked))}),i.jsx(Yo,{label:"Enable Invisible Watermark",isDisabled:!v,isChecked:V,onChange:X=>n(pM(X.target.checked))})]}),i.jsxs(Gl,{children:[i.jsx(Xs,{size:"sm",children:r("settings.ui")}),i.jsx(Yo,{label:r("common.darkMode"),isChecked:Y==="dark",onChange:ae}),i.jsx(Yo,{label:r("settings.useSlidersForAll"),isChecked:O,onChange:X=>n(hM(X.target.checked))}),i.jsx(Yo,{label:r("settings.showProgressInViewer"),isChecked:R,onChange:X=>n(B_(X.target.checked))}),i.jsx(Yo,{label:r("settings.antialiasProgressImages"),isChecked:A,onChange:X=>n(mM(X.target.checked))}),o&&i.jsx(Yo,{label:r("settings.alternateCanvasLayout"),useBadge:!0,badgeLabel:r("settings.beta"),isChecked:E,onChange:X=>n(gM(X.target.checked))}),p&&i.jsx(Yo,{label:r("settings.enableNodesEditor"),useBadge:!0,isChecked:Q,onChange:W}),h&&i.jsx(Yr,{disabled:!ye,label:r("common.languagePickerLabel"),value:ue,data:Object.entries(pee).map(([X,K])=>({value:X,label:K})),onChange:D})]}),s&&i.jsxs(Gl,{children:[i.jsx(Xs,{size:"sm",children:r("settings.developer")}),i.jsx(Yo,{label:r("settings.shouldLogToConsole"),isChecked:T,onChange:L}),i.jsx(Yr,{disabled:!T,label:r("settings.consoleLogLevel"),onChange:G,value:M,data:vM.concat()}),i.jsx(Yo,{label:r("settings.enableImageDebugging"),isChecked:P,onChange:X=>n(bM(X.target.checked))})]}),d&&i.jsx(iee,{}),i.jsxs(Gl,{children:[i.jsx(Xs,{size:"sm",children:r("settings.resetWebUI")}),i.jsx(rn,{colorScheme:"error",onClick:q,children:r("settings.resetWebUI")}),a&&i.jsxs(i.Fragment,{children:[i.jsx(tt,{variant:"subtext",children:r("settings.resetWebUIDesc1")}),i.jsx(tt,{variant:"subtext",children:r("settings.resetWebUIDesc2")})]})]})]})}),i.jsx(Oa,{children:i.jsx(rn,{onClick:y,children:r("common.close")})})]})]}),i.jsxs(Qu,{closeOnOverlayClick:!1,isOpen:S,onClose:_,isCentered:!0,children:[i.jsx(Ma,{backdropFilter:"blur(40px)"}),i.jsxs(Ju,{children:[i.jsx(Ra,{}),i.jsx(Da,{children:i.jsx(H,{justifyContent:"center",children:i.jsx(tt,{fontSize:"lg",children:i.jsx(tt,{children:r("settings.resetComplete")})})})}),i.jsx(Oa,{})]})]})]})},gee=fe(mo,e=>{const{isConnected:t,isProcessing:n,statusTranslationKey:r,currentIteration:o,totalIterations:s,currentStatusHasSteps:a}=e;return{isConnected:t,isProcessing:n,currentIteration:o,totalIterations:s,statusTranslationKey:r,currentStatusHasSteps:a}},Ge),pk={ok:"green.400",working:"yellow.400",error:"red.400"},hk={ok:"green.600",working:"yellow.500",error:"red.500"},vee=()=>{const{isConnected:e,isProcessing:t,currentIteration:n,totalIterations:r,statusTranslationKey:o}=z(gee),{t:s}=be(),a=f.useRef(null),c=f.useMemo(()=>t?"working":e?"ok":"error",[t,e]),d=f.useMemo(()=>{if(n&&r)return` (${n}/${r})`},[n,r]),p=rO(a);return i.jsxs(H,{ref:a,h:"full",px:2,alignItems:"center",gap:5,children:[i.jsx(Fo,{children:p&&i.jsx(Xr.div,{initial:{opacity:0},animate:{opacity:1,transition:{duration:.15}},exit:{opacity:0,transition:{delay:.8}},children:i.jsxs(tt,{sx:{fontSize:"sm",fontWeight:"600",pb:"1px",userSelect:"none",color:hk[c],_dark:{color:pk[c]}},children:[s(o),d]})},"statusText")}),i.jsx(Kr,{as:VH,sx:{boxSize:"0.5rem",color:hk[c],_dark:{color:pk[c]}}})]})},bee=()=>{const{t:e}=be(),t=ar("bugLink").isFeatureEnabled,n=ar("discordLink").isFeatureEnabled,r=ar("githubLink").isFeatureEnabled,o="http://github.com/invoke-ai/InvokeAI",s="https://discord.gg/ZmtBAhwWhy";return i.jsxs(H,{sx:{gap:2,alignItems:"center"},children:[i.jsx(oO,{}),i.jsx(fl,{}),i.jsx(vee,{}),i.jsxs(kd,{children:[i.jsx(_d,{as:Le,variant:"link","aria-label":e("accessibility.menu"),icon:i.jsx(FH,{}),sx:{boxSize:8}}),i.jsxs(zc,{motionProps:nm,children:[i.jsxs(Xu,{title:e("common.communityLabel"),children:[r&&i.jsx(_r,{as:"a",href:o,target:"_blank",icon:i.jsx(TH,{}),children:e("common.githubLabel")}),t&&i.jsx(_r,{as:"a",href:`${o}/issues`,target:"_blank",icon:i.jsx(HH,{}),children:e("common.reportBugLabel")}),n&&i.jsx(_r,{as:"a",href:s,target:"_blank",icon:i.jsx(DH,{}),children:e("common.discordLabel")})]}),i.jsxs(Xu,{title:e("common.settingsLabel"),children:[i.jsx(ZZ,{children:i.jsx(_r,{as:"button",icon:i.jsx(oW,{}),children:e("common.hotkeysLabel")})}),i.jsx(mee,{children:i.jsx(_r,{as:"button",icon:i.jsx(UH,{}),children:e("common.settingsLabel")})})]})]})]})]})},yee=f.memo(bee);function xee(e){return rt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"}},{tag:"path",attr:{d:"M16.5 9c-.42 0-.83.04-1.24.11L1.01 3 1 10l9 2-9 2 .01 7 8.07-3.46C9.59 21.19 12.71 24 16.5 24c4.14 0 7.5-3.36 7.5-7.5S20.64 9 16.5 9zm0 13c-3.03 0-5.5-2.47-5.5-5.5s2.47-5.5 5.5-5.5 5.5 2.47 5.5 5.5-2.47 5.5-5.5 5.5z"}},{tag:"path",attr:{d:"M18.27 14.03l-1.77 1.76-1.77-1.76-.7.7 1.76 1.77-1.76 1.77.7.7 1.77-1.76 1.77 1.76.7-.7-1.76-1.77 1.76-1.77z"}}]})(e)}function wee(e){return rt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"}},{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0V0z"}},{tag:"path",attr:{d:"M17 16l-4-4V8.82C14.16 8.4 15 7.3 15 6c0-1.66-1.34-3-3-3S9 4.34 9 6c0 1.3.84 2.4 2 2.82V12l-4 4H3v5h5v-3.05l4-4.2 4 4.2V21h5v-5h-4z"}}]})(e)}function See(e){return rt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"}},{tag:"path",attr:{d:"M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM8 20H4v-4h4v4zm0-6H4v-4h4v4zm0-6H4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4z"}}]})(e)}function Cee(e){return rt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"}},{tag:"path",attr:{d:"M22 16V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2zm-11-4l2.03 2.71L16 11l4 5H8l3-4zM2 6v14c0 1.1.9 2 2 2h14v-2H4V6H2z"}}]})(e)}function kee(e){return rt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"}},{tag:"path",attr:{d:"M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"}}]})(e)}function sO(e){return rt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0V0z"}},{tag:"path",attr:{d:"M16 17.01V10h-2v7.01h-3L15 21l4-3.99h-3zM9 3L5 6.99h3V14h2V6.99h3L9 3zm7 14.01V10h-2v7.01h-3L15 21l4-3.99h-3zM9 3L5 6.99h3V14h2V6.99h3L9 3z"}}]})(e)}const _ee=fe(mo,e=>{const{isUploading:t}=e;let n="";return t&&(n="Uploading..."),{tooltip:n,shouldShow:t}}),Pee=()=>{const{shouldShow:e,tooltip:t}=z(_ee);return e?i.jsx(H,{sx:{alignItems:"center",justifyContent:"center",color:"base.600"},children:i.jsx(wn,{label:t,placement:"right",hasArrow:!0,children:i.jsx(dl,{})})}):null},jee=f.memo(Pee),aO=e=>e.config,{createElement:jc,createContext:Iee,forwardRef:iO,useCallback:ri,useContext:lO,useEffect:ja,useImperativeHandle:cO,useLayoutEffect:Eee,useMemo:Oee,useRef:Zo,useState:Bu}=N1,mk=N1["useId".toString()],Ree=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",qh=Ree?Eee:()=>{},Mee=typeof mk=="function"?mk:()=>null;let Dee=0;function My(e=null){const t=Mee(),n=Zo(e||t||null);return n.current===null&&(n.current=""+Dee++),n.current}const Um=Iee(null);Um.displayName="PanelGroupContext";function uO({children:e=null,className:t="",collapsedSize:n=0,collapsible:r=!1,defaultSize:o=null,forwardedRef:s,id:a=null,maxSize:c=100,minSize:d=10,onCollapse:p=null,onResize:h=null,order:m=null,style:v={},tagName:b="div"}){const w=lO(Um);if(w===null)throw Error("Panel components must be rendered within a PanelGroup container");const y=My(a),{collapsePanel:S,expandPanel:k,getPanelStyle:_,registerPanel:I,resizePanel:P,unregisterPanel:E}=w,O=Zo({onCollapse:p,onResize:h});if(ja(()=>{O.current.onCollapse=p,O.current.onResize=h}),d<0||d>100)throw Error(`Panel minSize must be between 0 and 100, but was ${d}`);if(c<0||c>100)throw Error(`Panel maxSize must be between 0 and 100, but was ${c}`);if(o!==null){if(o<0||o>100)throw Error(`Panel defaultSize must be between 0 and 100, but was ${o}`);d>o&&!r&&(console.error(`Panel minSize ${d} cannot be greater than defaultSize ${o}`),o=d)}const R=_(y,o),M=Zo({size:gk(R)}),T=Zo({callbacksRef:O,collapsedSize:n,collapsible:r,defaultSize:o,id:y,maxSize:c,minSize:d,order:m});return qh(()=>{M.current.size=gk(R),T.current.callbacksRef=O,T.current.collapsedSize=n,T.current.collapsible=r,T.current.defaultSize=o,T.current.id=y,T.current.maxSize=c,T.current.minSize=d,T.current.order=m}),qh(()=>(I(y,T),()=>{E(y)}),[m,y,I,E]),cO(s,()=>({collapse:()=>S(y),expand:()=>k(y),getCollapsed(){return M.current.size===0},getSize(){return M.current.size},resize:A=>P(y,A)}),[S,k,y,P]),jc(b,{children:e,className:t,"data-panel":"","data-panel-collapsible":r||void 0,"data-panel-id":y,"data-panel-size":parseFloat(""+R.flexGrow).toFixed(1),id:`data-panel-id-${y}`,style:{...R,...v}})}const sd=iO((e,t)=>jc(uO,{...e,forwardedRef:t}));uO.displayName="Panel";sd.displayName="forwardRef(Panel)";function gk(e){const{flexGrow:t}=e;return typeof t=="string"?parseFloat(t):t}const ul=10;function Iu(e,t,n,r,o,s,a,c){const{sizes:d}=c||{},p=d||s;if(o===0)return p;const h=Qo(t),m=p.concat();let v=0;{const y=o<0?r:n,S=h.findIndex(P=>P.current.id===y),k=h[S],_=p[S],I=vk(k,Math.abs(o),_,e);if(_===I)return p;I===0&&_>0&&a.set(y,_),o=o<0?_-I:I-_}let b=o<0?n:r,w=h.findIndex(y=>y.current.id===b);for(;;){const y=h[w],S=p[w],k=Math.abs(o)-Math.abs(v),_=vk(y,0-k,S,e);if(S!==_&&(_===0&&S>0&&a.set(y.current.id,S),v+=S-_,m[w]=_,v.toPrecision(ul).localeCompare(Math.abs(o).toPrecision(ul),void 0,{numeric:!0})>=0))break;if(o<0){if(--w<0)break}else if(++w>=h.length)break}return v===0?p:(b=o<0?r:n,w=h.findIndex(y=>y.current.id===b),m[w]=p[w]+v,m)}function Wl(e,t,n){t.forEach((r,o)=>{const{callbacksRef:s,collapsedSize:a,collapsible:c,id:d}=e[o].current,p=n[d];if(p!==r){n[d]=r;const{onCollapse:h,onResize:m}=s.current;m&&m(r,p),c&&h&&((p==null||p===a)&&r!==a?h(!1):p!==a&&r===a&&h(!0))}})}function Z0(e,t){if(t.length<2)return[null,null];const n=t.findIndex(a=>a.current.id===e);if(n<0)return[null,null];const r=n===t.length-1,o=r?t[n-1].current.id:e,s=r?e:t[n+1].current.id;return[o,s]}function dO(e,t,n){if(e.size===1)return"100";const o=Qo(e).findIndex(a=>a.current.id===t),s=n[o];return s==null?"0":s.toPrecision(ul)}function Tee(e){const t=document.querySelector(`[data-panel-id="${e}"]`);return t||null}function Dy(e){const t=document.querySelector(`[data-panel-group-id="${e}"]`);return t||null}function Gm(e){const t=document.querySelector(`[data-panel-resize-handle-id="${e}"]`);return t||null}function Aee(e){return fO().findIndex(r=>r.getAttribute("data-panel-resize-handle-id")===e)??null}function fO(){return Array.from(document.querySelectorAll("[data-panel-resize-handle-id]"))}function pO(e){return Array.from(document.querySelectorAll(`[data-panel-resize-handle-id][data-panel-group-id="${e}"]`))}function Ty(e,t,n){var d,p,h,m;const r=Gm(t),o=pO(e),s=r?o.indexOf(r):-1,a=((p=(d=n[s])==null?void 0:d.current)==null?void 0:p.id)??null,c=((m=(h=n[s+1])==null?void 0:h.current)==null?void 0:m.id)??null;return[a,c]}function Qo(e){return Array.from(e.values()).sort((t,n)=>{const r=t.current.order,o=n.current.order;return r==null&&o==null?0:r==null?-1:o==null?1:r-o})}function vk(e,t,n,r){var h;const o=n+t,{collapsedSize:s,collapsible:a,maxSize:c,minSize:d}=e.current;if(a){if(n>s){if(o<=d/2+s)return s}else if(!((h=r==null?void 0:r.type)==null?void 0:h.startsWith("key"))&&o{const{direction:a,panels:c}=e.current,d=Dy(t),{height:p,width:h}=d.getBoundingClientRect(),v=pO(t).map(b=>{const w=b.getAttribute("data-panel-resize-handle-id"),y=Qo(c),[S,k]=Ty(t,w,y);if(S==null||k==null)return()=>{};let _=0,I=100,P=0,E=0;y.forEach($=>{$.current.id===S?(I=$.current.maxSize,_=$.current.minSize):(P+=$.current.minSize,E+=$.current.maxSize)});const O=Math.min(I,100-P),R=Math.max(_,(y.length-1)*100-E),M=dO(c,S,o);b.setAttribute("aria-valuemax",""+Math.round(O)),b.setAttribute("aria-valuemin",""+Math.round(R)),b.setAttribute("aria-valuenow",""+Math.round(parseInt(M)));const T=$=>{if(!$.defaultPrevented)switch($.key){case"Enter":{$.preventDefault();const Q=y.findIndex(B=>B.current.id===S);if(Q>=0){const B=y[Q],V=o[Q];if(V!=null){let q=0;V.toPrecision(ul)<=B.current.minSize.toPrecision(ul)?q=a==="horizontal"?h:p:q=-(a==="horizontal"?h:p);const G=Iu($,c,S,k,q,o,s.current,null);o!==G&&r(G)}}break}}};b.addEventListener("keydown",T);const A=Tee(S);return A!=null&&b.setAttribute("aria-controls",A.id),()=>{b.removeAttribute("aria-valuemax"),b.removeAttribute("aria-valuemin"),b.removeAttribute("aria-valuenow"),b.removeEventListener("keydown",T),A!=null&&b.removeAttribute("aria-controls")}});return()=>{v.forEach(b=>b())}},[e,t,n,s,r,o])}function $ee({disabled:e,handleId:t,resizeHandler:n}){ja(()=>{if(e||n==null)return;const r=Gm(t);if(r==null)return;const o=s=>{if(!s.defaultPrevented)switch(s.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{s.preventDefault(),n(s);break}case"F6":{s.preventDefault();const a=fO(),c=Aee(t);hO(c!==null);const d=s.shiftKey?c>0?c-1:a.length-1:c+1{r.removeEventListener("keydown",o)}},[e,t,n])}function zee(e,t){if(e.length!==t.length)return!1;for(let n=0;nR.current.id===P),O=r[E];if(O.current.collapsible){const R=h[E];(R===0||R.toPrecision(ul)===O.current.minSize.toPrecision(ul))&&(k=k<0?-O.current.minSize*w:O.current.minSize*w)}return k}else return mO(e,n,o,c,d)}function Bee(e){return e.type==="keydown"}function b1(e){return e.type.startsWith("mouse")}function y1(e){return e.type.startsWith("touch")}let x1=null,qi=null;function gO(e){switch(e){case"horizontal":return"ew-resize";case"horizontal-max":return"w-resize";case"horizontal-min":return"e-resize";case"vertical":return"ns-resize";case"vertical-max":return"n-resize";case"vertical-min":return"s-resize"}}function Fee(){qi!==null&&(document.head.removeChild(qi),x1=null,qi=null)}function ev(e){if(x1===e)return;x1=e;const t=gO(e);qi===null&&(qi=document.createElement("style"),document.head.appendChild(qi)),qi.innerHTML=`*{cursor: ${t}!important;}`}function Hee(e,t=10){let n=null;return(...o)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...o)},t)}}function vO(e){return e.map(t=>{const{minSize:n,order:r}=t.current;return r?`${r}:${n}`:`${n}`}).sort((t,n)=>t.localeCompare(n)).join(",")}function bO(e,t){try{const n=t.getItem(`PanelGroup:sizes:${e}`);if(n){const r=JSON.parse(n);if(typeof r=="object"&&r!=null)return r}}catch{}return null}function Wee(e,t,n){const r=bO(e,n);if(r){const o=vO(t);return r[o]??null}return null}function Vee(e,t,n,r){const o=vO(t),s=bO(e,r)||{};s[o]=n;try{r.setItem(`PanelGroup:sizes:${e}`,JSON.stringify(s))}catch(a){console.error(a)}}const tv={};function bk(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}const Eu={getItem:e=>(bk(Eu),Eu.getItem(e)),setItem:(e,t)=>{bk(Eu),Eu.setItem(e,t)}};function yO({autoSaveId:e,children:t=null,className:n="",direction:r,disablePointerEventsDuringResize:o=!1,forwardedRef:s,id:a=null,onLayout:c,storage:d=Eu,style:p={},tagName:h="div"}){const m=My(a),[v,b]=Bu(null),[w,y]=Bu(new Map),S=Zo(null),k=Zo({onLayout:c});ja(()=>{k.current.onLayout=c});const _=Zo({}),[I,P]=Bu([]),E=Zo(new Map),O=Zo(0),R=Zo({direction:r,panels:w,sizes:I});cO(s,()=>({getLayout:()=>{const{sizes:D}=R.current;return D},setLayout:D=>{const L=D.reduce((ye,ue)=>ye+ue,0);hO(L===100,"Panel sizes must add up to 100%");const{panels:W}=R.current,Y=_.current,ae=Qo(W);P(D),Wl(ae,D,Y)}}),[]),qh(()=>{R.current.direction=r,R.current.panels=w,R.current.sizes=I}),Nee({committedValuesRef:R,groupId:m,panels:w,setSizes:P,sizes:I,panelSizeBeforeCollapse:E}),ja(()=>{const{onLayout:D}=k.current,{panels:L,sizes:W}=R.current;if(W.length>0){D&&D(W);const Y=_.current,ae=Qo(L);Wl(ae,W,Y)}},[I]),qh(()=>{if(R.current.sizes.length===w.size)return;let L=null;if(e){const W=Qo(w);L=Wee(e,W,d)}if(L!=null)P(L);else{const W=Qo(w);let Y=0,ae=0,ye=0;if(W.forEach(ue=>{ye+=ue.current.minSize,ue.current.defaultSize===null?Y++:ae+=ue.current.defaultSize}),ae>100)throw new Error("Default panel sizes cannot exceed 100%");if(W.length>1&&Y===0&&ae!==100)throw new Error("Invalid default sizes specified for panels");if(ye>100)throw new Error("Minimum panel sizes cannot exceed 100%");P(W.map(ue=>ue.current.defaultSize===null?(100-ae)/Y:ue.current.defaultSize))}},[e,w,d]),ja(()=>{if(e){if(I.length===0||I.length!==w.size)return;const D=Qo(w);tv[e]||(tv[e]=Hee(Vee,100)),tv[e](e,D,I,d)}},[e,w,I,d]);const M=ri((D,L)=>{const{panels:W}=R.current;return W.size===0?{flexBasis:0,flexGrow:L??void 0,flexShrink:1,overflow:"hidden"}:{flexBasis:0,flexGrow:dO(W,D,I),flexShrink:1,overflow:"hidden",pointerEvents:o&&v!==null?"none":void 0}},[v,o,I]),T=ri((D,L)=>{y(W=>{if(W.has(D))return W;const Y=new Map(W);return Y.set(D,L),Y})},[]),A=ri(D=>W=>{W.preventDefault();const{direction:Y,panels:ae,sizes:ye}=R.current,ue=Qo(ae),[X,K]=Ty(m,D,ue);if(X==null||K==null)return;let U=Lee(W,m,D,ue,Y,ye,S.current);if(U===0)return;const re=Dy(m).getBoundingClientRect(),oe=Y==="horizontal";document.dir==="rtl"&&oe&&(U=-U);const pe=oe?re.width:re.height,le=U/pe*100,ge=Iu(W,ae,X,K,le,ye,E.current,S.current),_e=!zee(ye,ge);if((b1(W)||y1(W))&&O.current!=le&&ev(_e?oe?"horizontal":"vertical":oe?U<0?"horizontal-min":"horizontal-max":U<0?"vertical-min":"vertical-max"),_e){const ie=_.current;P(ge),Wl(ue,ge,ie)}O.current=le},[m]),$=ri(D=>{y(L=>{if(!L.has(D))return L;const W=new Map(L);return W.delete(D),W})},[]),Q=ri(D=>{const{panels:L,sizes:W}=R.current,Y=L.get(D);if(Y==null)return;const{collapsedSize:ae,collapsible:ye}=Y.current;if(!ye)return;const ue=Qo(L),X=ue.indexOf(Y);if(X<0)return;const K=W[X];if(K===ae)return;E.current.set(D,K);const[U,se]=Z0(D,ue);if(U==null||se==null)return;const oe=X===ue.length-1?K:ae-K,pe=Iu(null,L,U,se,oe,W,E.current,null);if(W!==pe){const le=_.current;P(pe),Wl(ue,pe,le)}},[]),B=ri(D=>{const{panels:L,sizes:W}=R.current,Y=L.get(D);if(Y==null)return;const{collapsedSize:ae,minSize:ye}=Y.current,ue=E.current.get(D)||ye;if(!ue)return;const X=Qo(L),K=X.indexOf(Y);if(K<0||W[K]!==ae)return;const[se,re]=Z0(D,X);if(se==null||re==null)return;const pe=K===X.length-1?ae-ue:ue,le=Iu(null,L,se,re,pe,W,E.current,null);if(W!==le){const ge=_.current;P(le),Wl(X,le,ge)}},[]),V=ri((D,L)=>{const{panels:W,sizes:Y}=R.current,ae=W.get(D);if(ae==null)return;const{collapsedSize:ye,collapsible:ue,maxSize:X,minSize:K}=ae.current,U=Qo(W),se=U.indexOf(ae);if(se<0)return;const re=Y[se];if(re===L)return;ue&&L===ye||(L=Math.min(X,Math.max(K,L)));const[oe,pe]=Z0(D,U);if(oe==null||pe==null)return;const ge=se===U.length-1?re-L:L-re,_e=Iu(null,W,oe,pe,ge,Y,E.current,null);if(Y!==_e){const ie=_.current;P(_e),Wl(U,_e,ie)}},[]),q=Oee(()=>({activeHandleId:v,collapsePanel:Q,direction:r,expandPanel:B,getPanelStyle:M,groupId:m,registerPanel:T,registerResizeHandle:A,resizePanel:V,startDragging:(D,L)=>{if(b(D),b1(L)||y1(L)){const W=Gm(D);S.current={dragHandleRect:W.getBoundingClientRect(),dragOffset:mO(L,D,r),sizes:R.current.sizes}}},stopDragging:()=>{Fee(),b(null),S.current=null},unregisterPanel:$}),[v,Q,r,B,M,m,T,A,V,$]),G={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return jc(Um.Provider,{children:jc(h,{children:t,className:n,"data-panel-group":"","data-panel-group-direction":r,"data-panel-group-id":m,style:{...G,...p}}),value:q})}const Ay=iO((e,t)=>jc(yO,{...e,forwardedRef:t}));yO.displayName="PanelGroup";Ay.displayName="forwardRef(PanelGroup)";function w1({children:e=null,className:t="",disabled:n=!1,id:r=null,onDragging:o,style:s={},tagName:a="div"}){const c=Zo(null),d=Zo({onDragging:o});ja(()=>{d.current.onDragging=o});const p=lO(Um);if(p===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{activeHandleId:h,direction:m,groupId:v,registerResizeHandle:b,startDragging:w,stopDragging:y}=p,S=My(r),k=h===S,[_,I]=Bu(!1),[P,E]=Bu(null),O=ri(()=>{c.current.blur(),y();const{onDragging:T}=d.current;T&&T(!1)},[y]);ja(()=>{if(n)E(null);else{const M=b(S);E(()=>M)}},[n,S,b]),ja(()=>{if(n||P==null||!k)return;const M=Q=>{P(Q)},T=Q=>{P(Q)},$=c.current.ownerDocument;return $.body.addEventListener("contextmenu",O),$.body.addEventListener("mousemove",M),$.body.addEventListener("touchmove",M),$.body.addEventListener("mouseleave",T),window.addEventListener("mouseup",O),window.addEventListener("touchend",O),()=>{$.body.removeEventListener("contextmenu",O),$.body.removeEventListener("mousemove",M),$.body.removeEventListener("touchmove",M),$.body.removeEventListener("mouseleave",T),window.removeEventListener("mouseup",O),window.removeEventListener("touchend",O)}},[m,n,k,P,O]),$ee({disabled:n,handleId:S,resizeHandler:P});const R={cursor:gO(m),touchAction:"none",userSelect:"none"};return jc(a,{children:e,className:t,"data-resize-handle-active":k?"pointer":_?"keyboard":void 0,"data-panel-group-direction":m,"data-panel-group-id":v,"data-panel-resize-handle-enabled":!n,"data-panel-resize-handle-id":S,onBlur:()=>I(!1),onFocus:()=>I(!0),onMouseDown:M=>{w(S,M.nativeEvent);const{onDragging:T}=d.current;T&&T(!0)},onMouseUp:O,onTouchCancel:O,onTouchEnd:O,onTouchStart:M=>{w(S,M.nativeEvent);const{onDragging:T}=d.current;T&&T(!0)},ref:c,role:"separator",style:{...R,...s},tabIndex:0})}w1.displayName="PanelResizeHandle";const Uee=(e,t,n,r="horizontal")=>{const o=f.useRef(null),[s,a]=f.useState(t),c=f.useCallback(()=>{var p,h;const d=(p=o.current)==null?void 0:p.getSize();d!==void 0&&d{const d=document.querySelector(`[data-panel-group-id="${n}"]`),p=document.querySelectorAll("[data-panel-resize-handle-id]");if(!d)return;const h=new ResizeObserver(()=>{let m=r==="horizontal"?d.getBoundingClientRect().width:d.getBoundingClientRect().height;p.forEach(v=>{m-=r==="horizontal"?v.getBoundingClientRect().width:v.getBoundingClientRect().height}),a(e/m*100)});return h.observe(d),p.forEach(m=>{h.observe(m)}),window.addEventListener("resize",c),()=>{h.disconnect(),window.removeEventListener("resize",c)}},[n,c,s,e,r]),{ref:o,minSizePct:s}},Gee=fe([Ye],e=>{const{initialImage:t}=e.generation;return{initialImage:t,isResetButtonDisabled:!t}},Ge),qee=()=>{const{initialImage:e}=z(Gee),{currentData:t}=os((e==null?void 0:e.imageName)??oo.skipToken),n=f.useMemo(()=>{if(t)return{id:"initial-image",payloadType:"IMAGE_DTO",payload:{imageDTO:t}}},[t]),r=f.useMemo(()=>({id:"initial-image",actionType:"SET_INITIAL_IMAGE"}),[]);return i.jsx(yi,{imageDTO:t,droppableData:r,draggableData:n,isUploadDisabled:!0,fitContainer:!0,dropLabel:"Set as Initial Image",noContentFallback:i.jsx(mi,{label:"No initial image selected"})})},Kee=fe([Ye],e=>{const{initialImage:t}=e.generation;return{isResetButtonDisabled:!t}},Ge),Yee={type:"SET_INITIAL_IMAGE"},Xee=()=>{const{isResetButtonDisabled:e}=z(Kee),t=te(),{getUploadButtonProps:n,getUploadInputProps:r}=Vm({postUploadAction:Yee}),o=f.useCallback(()=>{t(yM())},[t]);return i.jsxs(H,{layerStyle:"first",sx:{position:"relative",flexDirection:"column",height:"full",width:"full",alignItems:"center",justifyContent:"center",borderRadius:"base",p:4,gap:4},children:[i.jsxs(H,{sx:{w:"full",flexWrap:"wrap",justifyContent:"center",alignItems:"center",gap:2},children:[i.jsx(tt,{sx:{fontWeight:600,userSelect:"none",color:"base.700",_dark:{color:"base.200"}},children:"Initial Image"}),i.jsx(fl,{}),i.jsx(Le,{tooltip:"Upload Initial Image","aria-label":"Upload Initial Image",icon:i.jsx(Md,{}),...n()}),i.jsx(Le,{tooltip:"Reset Initial Image","aria-label":"Reset Initial Image",icon:i.jsx(Hb,{}),onClick:o,isDisabled:e})]}),i.jsx(qee,{}),i.jsx("input",{...r()})]})},Qee=e=>{const{label:t,activeLabel:n,children:r,defaultIsOpen:o=!1}=e,{isOpen:s,onToggle:a}=ss({defaultIsOpen:o}),{colorMode:c}=Ds();return i.jsxs(Oe,{children:[i.jsxs(H,{onClick:a,sx:{alignItems:"center",p:2,px:4,gap:2,borderTopRadius:"base",borderBottomRadius:s?0:"base",bg:s?ze("base.200","base.750")(c):ze("base.150","base.800")(c),color:ze("base.900","base.100")(c),_hover:{bg:s?ze("base.250","base.700")(c):ze("base.200","base.750")(c)},fontSize:"sm",fontWeight:600,cursor:"pointer",transitionProperty:"common",transitionDuration:"normal",userSelect:"none"},children:[t,i.jsx(Fo,{children:n&&i.jsx(Xr.div,{initial:{opacity:0},animate:{opacity:1,transition:{duration:.1}},exit:{opacity:0,transition:{duration:.1}},children:i.jsx(tt,{sx:{color:"accent.500",_dark:{color:"accent.300"}},children:n})},"statusText")}),i.jsx(fl,{}),i.jsx(ay,{sx:{w:"1rem",h:"1rem",transform:s?"rotate(0deg)":"rotate(180deg)",transitionProperty:"common",transitionDuration:"normal"}})]}),i.jsx(sm,{in:s,animateOpacity:!0,style:{overflow:"unset"},children:i.jsx(Oe,{sx:{p:4,borderBottomRadius:"base",bg:"base.100",_dark:{bg:"base.800"}},children:r})})]})},Oo=f.memo(Qee),Jee=fe(Ye,e=>{const{combinatorial:t,isEnabled:n}=e.dynamicPrompts;return{combinatorial:t,isDisabled:!n}},Ge),Zee=()=>{const{combinatorial:e,isDisabled:t}=z(Jee),n=te(),r=f.useCallback(()=>{n(xM())},[n]);return i.jsx(wr,{isDisabled:t,label:"Combinatorial Generation",isChecked:e,onChange:r})},ete=fe(Ye,e=>{const{isEnabled:t}=e.dynamicPrompts;return{isEnabled:t}},Ge),tte=()=>{const e=te(),{isEnabled:t}=z(ete),n=f.useCallback(()=>{e(wM())},[e]);return i.jsx(wr,{label:"Enable Dynamic Prompts",isChecked:t,onChange:n})},nte=fe(Ye,e=>{const{maxPrompts:t,combinatorial:n,isEnabled:r}=e.dynamicPrompts,{min:o,sliderMax:s,inputMax:a}=e.config.sd.dynamicPrompts.maxPrompts;return{maxPrompts:t,min:o,sliderMax:s,inputMax:a,isDisabled:!r||!n}},Ge),rte=()=>{const{maxPrompts:e,min:t,sliderMax:n,inputMax:r,isDisabled:o}=z(nte),s=te(),a=f.useCallback(d=>{s(SM(d))},[s]),c=f.useCallback(()=>{s(CM())},[s]);return i.jsx(_t,{label:"Max Prompts",isDisabled:o,min:t,max:n,value:e,onChange:a,sliderNumberInputProps:{max:r},withSliderMarks:!0,withInput:!0,withReset:!0,handleReset:c})},ote=fe(Ye,e=>{const{isEnabled:t}=e.dynamicPrompts;return{activeLabel:t?"Enabled":void 0}},Ge),zd=()=>{const{activeLabel:e}=z(ote);return ar("dynamicPrompting").isFeatureEnabled?i.jsx(Oo,{label:"Dynamic Prompts",activeLabel:e,children:i.jsxs(H,{sx:{gap:2,flexDir:"column"},children:[i.jsx(tte,{}),i.jsx(Zee,{}),i.jsx(rte,{})]})}):null},Ny=e=>{e.stopPropagation()},ste=Te((e,t)=>{const n=te(),r=f.useCallback(s=>{s.shiftKey&&n(_o(!0))},[n]),o=f.useCallback(s=>{s.shiftKey||n(_o(!1))},[n]);return i.jsx(W5,{ref:t,onPaste:Ny,onKeyDown:r,onKeyUp:o,...e})}),qm=f.memo(ste),ate=e=>{const{onClick:t}=e;return i.jsx(Le,{size:"sm","aria-label":"Add Embedding",tooltip:"Add Embedding",icon:i.jsx(Lb,{}),sx:{p:2,color:"base.500",_hover:{color:"base.600"},_active:{color:"base.700"},_dark:{color:"base.500",_hover:{color:"base.400"},_active:{color:"base.300"}}},variant:"link",onClick:t})},Km=f.memo(ate),$y="28rem",Ym=e=>{const{onSelect:t,isOpen:n,onClose:r,children:o}=e,{data:s}=kM(),a=f.useRef(null),c=z(h=>h.generation.model),d=f.useMemo(()=>{if(!s)return[];const h=[];return jo(s.entities,(m,v)=>{if(!m)return;const b=(c==null?void 0:c.base_model)!==m.base_model;h.push({value:m.model_name,label:m.model_name,group:vr[m.base_model],disabled:b,tooltip:b?`Incompatible base model: ${m.base_model}`:void 0})}),h.sort((m,v)=>{var b;return m.label&&v.label?(b=m.label)!=null&&b.localeCompare(v.label)?-1:1:-1}),h.sort((m,v)=>m.disabled&&!v.disabled?1:-1)},[s,c==null?void 0:c.base_model]),p=f.useCallback(h=>{h&&t(h)},[t]);return i.jsxs(Tb,{initialFocusRef:a,isOpen:n,onClose:r,placement:"bottom",openDelay:0,closeDelay:0,closeOnBlur:!0,returnFocusOnClose:!0,children:[i.jsx(Db,{children:o}),i.jsx(Ab,{sx:{p:0,top:-1,shadow:"dark-lg",borderColor:"accent.300",borderWidth:"2px",borderStyle:"solid",_dark:{borderColor:"accent.400"}},children:i.jsx(x5,{sx:{p:0,w:`calc(${$y} - 2rem )`},children:d.length===0?i.jsx(H,{sx:{justifyContent:"center",p:2,fontSize:"sm",color:"base.500",_dark:{color:"base.700"}},children:i.jsx(tt,{children:"No Embeddings Loaded"})}):i.jsx(sr,{inputRef:a,autoFocus:!0,placeholder:"Add Embedding",value:null,data:d,nothingFound:"No matching Embeddings",itemComponent:Oi,disabled:d.length===0,onDropdownClose:r,filter:(h,m)=>{var v;return((v=m.label)==null?void 0:v.toLowerCase().includes(h.toLowerCase().trim()))||m.value.toLowerCase().includes(h.toLowerCase().trim())},onChange:p})})})]})},Ld=()=>{const e=z(m=>m.generation.negativePrompt),t=f.useRef(null),{isOpen:n,onClose:r,onOpen:o}=ss(),s=te(),{t:a}=be(),c=f.useCallback(m=>{s(Mu(m.target.value))},[s]),d=f.useCallback(m=>{m.key==="<"&&o()},[o]),p=f.useCallback(m=>{if(!t.current)return;const v=t.current.selectionStart;if(v===void 0)return;let b=e.slice(0,v);b[b.length-1]!=="<"&&(b+="<"),b+=`${m}>`;const w=b.length;b+=e.slice(v),_i.flushSync(()=>{s(Mu(b))}),t.current.selectionEnd=w,r()},[s,r,e]),h=ar("embedding").isFeatureEnabled;return i.jsxs(ho,{children:[i.jsx(Ym,{isOpen:n,onClose:r,onSelect:p,children:i.jsx(qm,{id:"negativePrompt",name:"negativePrompt",ref:t,value:e,placeholder:a("parameters.negativePromptPlaceholder"),onChange:c,resize:"vertical",fontSize:"sm",minH:16,...h&&{onKeyDown:d}})}),!n&&h&&i.jsx(Oe,{sx:{position:"absolute",top:0,insetInlineEnd:0},children:i.jsx(Km,{onClick:o})})]})},ite=fe([Ye,Kn],(e,t)=>{const{generation:n,system:r}=e,{initialImage:o}=n,{isProcessing:s,isConnected:a}=r;let c=!0;const d=[];t==="img2img"&&!o&&(c=!1,d.push("No initial image selected"));const{isSuccess:p}=_M.endpoints.getMainModels.select(W1)(e);return p||(c=!1,d.push("Models are not loaded")),s&&(c=!1,d.push("System Busy")),a||(c=!1,d.push("System Disconnected")),jo(e.controlNet.controlNets,(h,m)=>{h.model||(c=!1,d.push(`ControlNet ${m} has no model selected.`))}),{isReady:c,reasonsWhyNotReady:d}},Ge),Bd=()=>{const{isReady:e}=z(ite);return e},lte=fe([Ye,Kn],({generation:e,ui:t},n)=>({shouldPinParametersPanel:t.shouldPinParametersPanel,prompt:e.positivePrompt,activeTabName:n}),{memoizeOptions:{resultEqualityCheck:Qt}}),Fd=()=>{const e=te(),{prompt:t,shouldPinParametersPanel:n,activeTabName:r}=z(lte),o=Bd(),s=f.useRef(null),{isOpen:a,onClose:c,onOpen:d}=ss(),{t:p}=be(),h=f.useCallback(w=>{e(Ru(w.target.value))},[e]);nt("alt+a",()=>{var w;(w=s.current)==null||w.focus()},[]);const m=f.useCallback(w=>{if(!s.current)return;const y=s.current.selectionStart;if(y===void 0)return;let S=t.slice(0,y);S[S.length-1]!=="<"&&(S+="<"),S+=`${w}>`;const k=S.length;S+=t.slice(y),_i.flushSync(()=>{e(Ru(S))}),s.current.selectionStart=k,s.current.selectionEnd=k,c()},[e,c,t]),v=ar("embedding").isFeatureEnabled,b=f.useCallback(w=>{w.key==="Enter"&&w.shiftKey===!1&&o&&(w.preventDefault(),e(ud()),e(dd(r))),v&&w.key==="<"&&d()},[o,e,r,d,v]);return i.jsxs(Oe,{position:"relative",children:[i.jsx(ho,{children:i.jsx(Ym,{isOpen:a,onClose:c,onSelect:m,children:i.jsx(qm,{id:"prompt",name:"prompt",ref:s,value:t,placeholder:p("parameters.positivePromptPlaceholder"),onChange:h,onKeyDown:b,resize:"vertical",minH:32})})}),!a&&v&&i.jsx(Oe,{sx:{position:"absolute",top:n?6:0,insetInlineEnd:0},children:i.jsx(Km,{onClick:d})})]})},cte=fe(Ye,e=>{const{shouldUseNoiseSettings:t,shouldUseCpuNoise:n}=e.generation;return{isDisabled:!t,shouldUseCpuNoise:n}},Ge),ute=()=>{const e=te(),{isDisabled:t,shouldUseCpuNoise:n}=z(cte),r=o=>e(PM(o.target.checked));return i.jsx(wr,{isDisabled:t,label:"Use CPU Noise",isChecked:n,onChange:r})},dte=fe(Ye,e=>{const{shouldUseNoiseSettings:t,threshold:n}=e.generation;return{isDisabled:!t,threshold:n}},Ge);function fte(){const e=te(),{threshold:t,isDisabled:n}=z(dte),{t:r}=be();return i.jsx(_t,{isDisabled:n,label:r("parameters.noiseThreshold"),min:0,max:20,step:.1,onChange:o=>e(H2(o)),handleReset:()=>e(H2(0)),value:t,withInput:!0,withReset:!0,withSliderMarks:!0})}const pte=()=>{const e=te(),t=z(r=>r.generation.shouldUseNoiseSettings),n=r=>e(jM(r.target.checked));return i.jsx(wr,{label:"Enable Noise Settings",isChecked:t,onChange:n})},hte=fe(Ye,e=>{const{shouldUseNoiseSettings:t,perlin:n}=e.generation;return{isDisabled:!t,perlin:n}},Ge);function mte(){const e=te(),{perlin:t,isDisabled:n}=z(hte),{t:r}=be();return i.jsx(_t,{isDisabled:n,label:r("parameters.perlinNoise"),min:0,max:1,step:.05,onChange:o=>e(W2(o)),handleReset:()=>e(W2(0)),value:t,withInput:!0,withReset:!0,withSliderMarks:!0})}const gte=fe(Ye,e=>{const{shouldUseNoiseSettings:t}=e.generation;return{activeLabel:t?"Enabled":void 0}},Ge),vte=()=>{const{t:e}=be(),t=ar("noise").isFeatureEnabled,n=ar("perlinNoise").isFeatureEnabled,r=ar("noiseThreshold").isFeatureEnabled,{activeLabel:o}=z(gte);return t?i.jsx(Oo,{label:e("parameters.noiseSettings"),activeLabel:o,children:i.jsxs(H,{sx:{gap:2,flexDirection:"column"},children:[i.jsx(pte,{}),i.jsx(ute,{}),n&&i.jsx(mte,{}),r&&i.jsx(fte,{})]})}):null},Xm=f.memo(vte),bte=fe(mo,e=>({isProcessing:e.isProcessing,isConnected:e.isConnected,isCancelable:e.isCancelable,currentIteration:e.currentIteration,totalIterations:e.totalIterations,sessionId:e.sessionId,cancelType:e.cancelType,isCancelScheduled:e.isCancelScheduled}),{memoizeOptions:{resultEqualityCheck:Qt}}),yte=e=>{const t=te(),{btnGroupWidth:n="auto",...r}=e,{isProcessing:o,isConnected:s,isCancelable:a,cancelType:c,isCancelScheduled:d,sessionId:p}=z(bte),h=f.useCallback(()=>{if(p){if(c==="scheduled"){t(IM());return}t(EM({session_id:p}))}},[t,p,c]),{t:m}=be(),v=f.useCallback(y=>{const S=Array.isArray(y)?y[0]:y;t(OM(S))},[t]);nt("shift+x",()=>{(s||o)&&a&&h()},[s,o,a]);const b=f.useMemo(()=>m(d?"parameters.cancel.isScheduled":c==="immediate"?"parameters.cancel.immediate":"parameters.cancel.schedule"),[m,c,d]),w=f.useMemo(()=>d?i.jsx(Lp,{}):c==="immediate"?i.jsx(kee,{}):i.jsx(xee,{}),[c,d]);return i.jsxs(nr,{isAttached:!0,width:n,children:[i.jsx(Le,{icon:w,tooltip:b,"aria-label":b,isDisabled:!s||!o||!a,onClick:h,colorScheme:"error",id:"cancel-button",...r}),i.jsxs(kd,{closeOnSelect:!1,children:[i.jsx(_d,{as:Le,tooltip:m("parameters.cancel.setType"),"aria-label":m("parameters.cancel.setType"),icon:i.jsx(UV,{w:"1em",h:"1em"}),paddingX:0,paddingY:0,colorScheme:"error",minWidth:5,...r}),i.jsx(zc,{minWidth:"240px",children:i.jsxs(l5,{value:c,title:"Cancel Type",type:"radio",onChange:v,children:[i.jsx(Up,{value:"immediate",children:m("parameters.cancel.immediate")}),i.jsx(Up,{value:"scheduled",children:m("parameters.cancel.schedule")})]})})]})]})},Qm=f.memo(yte),xte=fe(mo,e=>({isProcessing:e.isProcessing,currentStep:e.currentStep,totalSteps:e.totalSteps,currentStatusHasSteps:e.currentStatusHasSteps}),{memoizeOptions:{resultEqualityCheck:Qt}}),wte=()=>{const{t:e}=be(),{isProcessing:t,currentStep:n,totalSteps:r,currentStatusHasSteps:o}=z(xte),s=n?Math.round(n*100/r):0;return i.jsx(S5,{value:s,"aria-label":e("accessibility.invokeProgressBar"),isIndeterminate:t&&!o,height:"full",colorScheme:"accent"})},xO=f.memo(wte),yk={_disabled:{bg:"none",color:"base.600",cursor:"not-allowed",_hover:{color:"base.600",bg:"none"}}},Ste=fe([Ye,Kn,jr],({gallery:e},t,n)=>{const{autoAddBoardId:r}=e;return{isBusy:n,autoAddBoardId:r,activeTabName:t}},Ge);function zy(e){const{iconButton:t=!1,...n}=e,r=te(),o=Bd(),{isBusy:s,autoAddBoardId:a,activeTabName:c}=z(Ste),d=Rm(a),p=f.useCallback(()=>{r(ud()),r(dd(c))},[r,c]),{t:h}=be();return nt(["ctrl+enter","meta+enter"],p,{enabled:()=>o,preventDefault:!0,enableOnFormTags:["input","textarea","select"]},[o,c]),i.jsx(Oe,{style:{flexGrow:4},position:"relative",children:i.jsxs(Oe,{style:{position:"relative"},children:[!o&&i.jsx(Oe,{borderRadius:"base",style:{position:"absolute",bottom:"0",left:"0",right:"0",height:"100%",overflow:"clip"},...n,children:i.jsx(xO,{})}),i.jsx(wn,{placement:"top",hasArrow:!0,openDelay:500,label:a?`Auto-Adding to ${d}`:void 0,children:t?i.jsx(Le,{"aria-label":h("parameters.invoke"),type:"submit",icon:i.jsx(y6,{}),isDisabled:!o||s,onClick:p,tooltip:h("parameters.invoke"),tooltipProps:{placement:"top"},colorScheme:"accent",id:"invoke-button",...n,sx:{w:"full",flexGrow:1,...s?yk:{}}}):i.jsx(rn,{"aria-label":h("parameters.invoke"),type:"submit",isDisabled:!o||s,onClick:p,colorScheme:"accent",id:"invoke-button",...n,sx:{w:"full",flexGrow:1,fontWeight:700,...s?yk:{}},children:"Invoke"})})]})})}const Hd=()=>i.jsxs(H,{gap:2,children:[i.jsx(zy,{}),i.jsx(Qm,{})]});function wO(){const e=z(r=>r.sdxl.shouldConcatSDXLStylePrompt),t=te(),n=r=>{t(RM(r.target.checked))};return i.jsx(Oe,{sx:{px:2},children:i.jsx(wr,{label:"Concat Style Prompt",tooltip:"Concatenates Basic Prompt with Style (Recommended)",isChecked:e,onChange:n})})}const Cte=fe([Ye,Kn],({sdxl:e},t)=>({prompt:e.negativeStylePrompt,activeTabName:t}),{memoizeOptions:{resultEqualityCheck:Qt}}),SO=()=>{const e=te(),{prompt:t,activeTabName:n}=z(Cte),r=Bd(),o=f.useRef(null),{isOpen:s,onClose:a,onOpen:c}=ss(),d=f.useCallback(v=>{e(V2(v.target.value))},[e]),p=f.useCallback(v=>{if(!o.current)return;const b=o.current.selectionStart;if(b===void 0)return;let w=t.slice(0,b);w[w.length-1]!=="<"&&(w+="<"),w+=`${v}>`;const y=w.length;w+=t.slice(b),_i.flushSync(()=>{e(V2(w))}),o.current.selectionStart=y,o.current.selectionEnd=y,a()},[e,a,t]),h=ar("embedding").isFeatureEnabled,m=f.useCallback(v=>{v.key==="Enter"&&v.shiftKey===!1&&r&&(v.preventDefault(),e(ud()),e(dd(n))),h&&v.key==="<"&&c()},[r,e,n,c,h]);return i.jsxs(Oe,{position:"relative",children:[i.jsx(ho,{children:i.jsx(Ym,{isOpen:s,onClose:a,onSelect:p,children:i.jsx(qm,{id:"prompt",name:"prompt",ref:o,value:t,placeholder:"Negative Style Prompt",onChange:d,onKeyDown:m,resize:"vertical",fontSize:"sm",minH:16})})}),!s&&h&&i.jsx(Oe,{sx:{position:"absolute",top:0,insetInlineEnd:0},children:i.jsx(Km,{onClick:c})})]})},kte=fe([Ye,Kn],({sdxl:e},t)=>({prompt:e.positiveStylePrompt,activeTabName:t}),{memoizeOptions:{resultEqualityCheck:Qt}}),CO=()=>{const e=te(),{prompt:t,activeTabName:n}=z(kte),r=Bd(),o=f.useRef(null),{isOpen:s,onClose:a,onOpen:c}=ss(),d=f.useCallback(v=>{e(U2(v.target.value))},[e]),p=f.useCallback(v=>{if(!o.current)return;const b=o.current.selectionStart;if(b===void 0)return;let w=t.slice(0,b);w[w.length-1]!=="<"&&(w+="<"),w+=`${v}>`;const y=w.length;w+=t.slice(b),_i.flushSync(()=>{e(U2(w))}),o.current.selectionStart=y,o.current.selectionEnd=y,a()},[e,a,t]),h=ar("embedding").isFeatureEnabled,m=f.useCallback(v=>{v.key==="Enter"&&v.shiftKey===!1&&r&&(v.preventDefault(),e(ud()),e(dd(n))),h&&v.key==="<"&&c()},[r,e,n,c,h]);return i.jsxs(Oe,{position:"relative",children:[i.jsx(ho,{children:i.jsx(Ym,{isOpen:s,onClose:a,onSelect:p,children:i.jsx(qm,{id:"prompt",name:"prompt",ref:o,value:t,placeholder:"Positive Style Prompt",onChange:d,onKeyDown:m,resize:"vertical",minH:16})})}),!s&&h&&i.jsx(Oe,{sx:{position:"absolute",top:0,insetInlineEnd:0},children:i.jsx(Km,{onClick:c})})]})},Uc=()=>{const{isRefinerAvailable:e}=na(V1,{selectFromResult:({data:t})=>({isRefinerAvailable:t?t.ids.length>0:!1})});return e},_te=fe([Ye],({sdxl:e,hotkeys:t})=>{const{refinerAestheticScore:n}=e,{shift:r}=t;return{refinerAestheticScore:n,shift:r}},Ge),Pte=()=>{const{refinerAestheticScore:e,shift:t}=z(_te),n=Uc(),r=te(),o=f.useCallback(a=>r(G2(a)),[r]),s=f.useCallback(()=>r(G2(6)),[r]);return i.jsx(_t,{label:"Aesthetic Score",step:t?.1:.5,min:1,max:10,onChange:o,handleReset:s,value:e,sliderNumberInputProps:{max:10},withInput:!0,withReset:!0,withSliderMarks:!0,isInteger:!1,isDisabled:!n})},jte=f.memo(Pte),Kh=/^-?(0\.)?\.?$/,Ite=e=>{const{label:t,isDisabled:n=!1,showStepper:r=!0,isInvalid:o,value:s,onChange:a,min:c,max:d,isInteger:p=!0,formControlProps:h,formLabelProps:m,numberInputFieldProps:v,numberInputStepperProps:b,tooltipProps:w,...y}=e,S=te(),[k,_]=f.useState(String(s));f.useEffect(()=>{!k.match(Kh)&&s!==Number(k)&&_(String(s))},[s,k]);const I=R=>{_(R),R.match(Kh)||a(p?Math.floor(Number(R)):Number(R))},P=R=>{const M=Es(p?Math.floor(Number(R.target.value)):Number(R.target.value),c,d);_(String(M)),a(M)},E=f.useCallback(R=>{R.shiftKey&&S(_o(!0))},[S]),O=f.useCallback(R=>{R.shiftKey||S(_o(!1))},[S]);return i.jsx(wn,{...w,children:i.jsxs(ho,{isDisabled:n,isInvalid:o,...h,children:[t&&i.jsx(zo,{...m,children:t}),i.jsxs(dm,{value:k,min:c,max:d,keepWithinRange:!0,clampValueOnBlur:!1,onChange:I,onBlur:P,...y,onPaste:Ny,children:[i.jsx(pm,{...v,onKeyDown:E,onKeyUp:O}),r&&i.jsxs(fm,{children:[i.jsx(mm,{...b}),i.jsx(hm,{...b})]})]})]})})},Gc=f.memo(Ite),Ete=fe([Ye],({sdxl:e,ui:t,hotkeys:n})=>{const{refinerCFGScale:r}=e,{shouldUseSliders:o}=t,{shift:s}=n;return{refinerCFGScale:r,shouldUseSliders:o,shift:s}},Ge),Ote=()=>{const{refinerCFGScale:e,shouldUseSliders:t,shift:n}=z(Ete),r=Uc(),o=te(),{t:s}=be(),a=f.useCallback(d=>o(q2(d)),[o]),c=f.useCallback(()=>o(q2(7)),[o]);return t?i.jsx(_t,{label:s("parameters.cfgScale"),step:n?.1:.5,min:1,max:20,onChange:a,handleReset:c,value:e,sliderNumberInputProps:{max:200},withInput:!0,withReset:!0,withSliderMarks:!0,isInteger:!1,isDisabled:!r}):i.jsx(Gc,{label:s("parameters.cfgScale"),step:.5,min:1,max:200,onChange:a,value:e,isInteger:!1,numberInputFieldProps:{textAlign:"center"},isDisabled:!r})},Rte=f.memo(Ote),Jm=e=>{const t=tm("models"),[n,r,o]=e.split("/"),s=MM.safeParse({base_model:n,model_name:o});if(!s.success){t.error({mainModelId:e,errors:s.error.format()},"Failed to parse main model id");return}return s.data};function Wd(e){const{iconMode:t=!1}=e,n=te(),{t:r}=be(),[o,{isLoading:s}]=DM(),a=()=>{o().unwrap().then(c=>{n(Dn(Bn({title:`${r("modelManager.modelsSynced")}`,status:"success"})))}).catch(c=>{c&&n(Dn(Bn({title:`${r("modelManager.modelSyncFailed")}`,status:"error"})))})};return t?i.jsx(Le,{icon:i.jsx(S6,{}),tooltip:r("modelManager.syncModels"),"aria-label":r("modelManager.syncModels"),isLoading:s,onClick:a,size:"sm"}):i.jsx(rn,{isLoading:s,onClick:a,minW:"max-content",children:"Sync Models"})}const Mte=fe(Ye,e=>({model:e.sdxl.refinerModel}),Ge),Dte=()=>{const e=te(),t=ar("syncModels").isFeatureEnabled,{model:n}=z(Mte),{data:r,isLoading:o}=na(V1),s=f.useMemo(()=>{if(!r)return[];const d=[];return jo(r.entities,(p,h)=>{p&&d.push({value:h,label:p.model_name,group:vr[p.base_model]})}),d},[r]),a=f.useMemo(()=>(r==null?void 0:r.entities[`${n==null?void 0:n.base_model}/main/${n==null?void 0:n.model_name}`])??null,[r==null?void 0:r.entities,n]),c=f.useCallback(d=>{if(!d)return;const p=Jm(d);p&&e(TM(p))},[e]);return o?i.jsx(sr,{label:"Refiner Model",placeholder:"Loading...",disabled:!0,data:[]}):i.jsxs(H,{w:"100%",alignItems:"center",gap:2,children:[i.jsx(sr,{tooltip:a==null?void 0:a.description,label:"Refiner Model",value:a==null?void 0:a.id,placeholder:s.length>0?"Select a model":"No models available",data:s,error:s.length===0,disabled:s.length===0,onChange:c,w:"100%"}),t&&i.jsx(Oe,{mt:7,children:i.jsx(Wd,{iconMode:!0})})]})},Tte=f.memo(Dte),Ate=fe(Ye,({ui:e,sdxl:t})=>{const{refinerScheduler:n}=t,{favoriteSchedulers:r}=e,o=cs(H1,(s,a)=>({value:a,label:s,group:r.includes(a)?"Favorites":void 0})).sort((s,a)=>s.label.localeCompare(a.label));return{refinerScheduler:n,data:o}},Ge),Nte=()=>{const e=te(),{t}=be(),{refinerScheduler:n,data:r}=z(Ate),o=Uc(),s=f.useCallback(a=>{a&&e(AM(a))},[e]);return i.jsx(sr,{w:"100%",label:t("parameters.scheduler"),value:n,data:r,onChange:s,disabled:!o})},$te=f.memo(Nte),zte=fe([Ye],({sdxl:e})=>{const{refinerStart:t}=e;return{refinerStart:t}},Ge),Lte=()=>{const{refinerStart:e}=z(zte),t=te(),n=Uc(),r=f.useCallback(s=>t(K2(s)),[t]),o=f.useCallback(()=>t(K2(.7)),[t]);return i.jsx(_t,{label:"Refiner Start",step:.01,min:0,max:1,onChange:r,handleReset:o,value:e,withInput:!0,withReset:!0,withSliderMarks:!0,isInteger:!1,isDisabled:!n})},Bte=f.memo(Lte),Fte=fe([Ye],({sdxl:e,ui:t})=>{const{refinerSteps:n}=e,{shouldUseSliders:r}=t;return{refinerSteps:n,shouldUseSliders:r}},Ge),Hte=()=>{const{refinerSteps:e,shouldUseSliders:t}=z(Fte),n=Uc(),r=te(),{t:o}=be(),s=f.useCallback(c=>{r(Y2(c))},[r]),a=f.useCallback(()=>{r(Y2(20))},[r]);return t?i.jsx(_t,{label:o("parameters.steps"),min:1,max:100,step:1,onChange:s,handleReset:a,value:e,withInput:!0,withReset:!0,withSliderMarks:!0,sliderNumberInputProps:{max:500},isDisabled:!n}):i.jsx(Gc,{label:o("parameters.steps"),min:1,max:500,step:1,onChange:s,value:e,numberInputFieldProps:{textAlign:"center"},isDisabled:!n})},Wte=f.memo(Hte);function Vte(){const e=z(o=>o.sdxl.shouldUseSDXLRefiner),t=Uc(),n=te(),r=o=>{n(NM(o.target.checked))};return i.jsx(wr,{label:"Use Refiner",isChecked:e,onChange:r,isDisabled:!t})}const Ute=fe(Ye,e=>{const{shouldUseSDXLRefiner:t}=e.sdxl,{shouldUseSliders:n}=e.ui;return{activeLabel:t?"Enabled":void 0,shouldUseSliders:n}},Ge),kO=()=>{const{activeLabel:e,shouldUseSliders:t}=z(Ute);return i.jsx(Oo,{label:"Refiner",activeLabel:e,children:i.jsxs(H,{sx:{gap:2,flexDir:"column"},children:[i.jsx(Vte,{}),i.jsx(Tte,{}),i.jsxs(H,{gap:2,flexDirection:t?"column":"row",children:[i.jsx(Wte,{}),i.jsx(Rte,{})]}),i.jsx($te,{}),i.jsx(jte,{}),i.jsx(Bte,{})]})})},Gte=fe([Ye],({generation:e,config:t,ui:n,hotkeys:r})=>{const{initial:o,min:s,sliderMax:a,inputMax:c}=t.sd.guidance,{cfgScale:d}=e,{shouldUseSliders:p}=n,{shift:h}=r;return{cfgScale:d,initial:o,min:s,sliderMax:a,inputMax:c,shouldUseSliders:p,shift:h}},Ge),qte=()=>{const{cfgScale:e,initial:t,min:n,sliderMax:r,inputMax:o,shouldUseSliders:s,shift:a}=z(Gte),c=te(),{t:d}=be(),p=f.useCallback(m=>c(Mp(m)),[c]),h=f.useCallback(()=>c(Mp(t)),[c,t]);return s?i.jsx(_t,{label:d("parameters.cfgScale"),step:a?.1:.5,min:n,max:r,onChange:p,handleReset:h,value:e,sliderNumberInputProps:{max:o},withInput:!0,withReset:!0,withSliderMarks:!0,isInteger:!1}):i.jsx(Gc,{label:d("parameters.cfgScale"),step:.5,min:n,max:o,onChange:p,value:e,isInteger:!1,numberInputFieldProps:{textAlign:"center"}})},xi=f.memo(qte),Kte=fe([Ye],e=>{const{initial:t,min:n,sliderMax:r,inputMax:o,fineStep:s,coarseStep:a}=e.config.sd.iterations,{iterations:c}=e.generation,{shouldUseSliders:d}=e.ui,p=e.dynamicPrompts.isEnabled&&e.dynamicPrompts.combinatorial,h=e.hotkeys.shift?s:a;return{iterations:c,initial:t,min:n,sliderMax:r,inputMax:o,step:h,shouldUseSliders:d,isDisabled:p}},Ge),Yte=()=>{const{iterations:e,initial:t,min:n,sliderMax:r,inputMax:o,step:s,shouldUseSliders:a,isDisabled:c}=z(Kte),d=te(),{t:p}=be(),h=f.useCallback(v=>{d(X2(v))},[d]),m=f.useCallback(()=>{d(X2(t))},[d,t]);return a?i.jsx(_t,{isDisabled:c,label:p("parameters.images"),step:s,min:n,max:r,onChange:h,handleReset:m,value:e,withInput:!0,withReset:!0,withSliderMarks:!0,sliderNumberInputProps:{max:o}}):i.jsx(Gc,{isDisabled:c,label:p("parameters.images"),step:s,min:n,max:o,onChange:h,value:e,numberInputFieldProps:{textAlign:"center"}})},wi=f.memo(Yte),Xte=fe(Ye,e=>({model:e.generation.model}),Ge),Qte=()=>{const e=te(),{t}=be(),{model:n}=z(Xte),r=ar("syncModels").isFeatureEnabled,{data:o,isLoading:s}=na(W1),a=z(Kn),c=f.useMemo(()=>{if(!o)return[];const h=[];return jo(o.entities,(m,v)=>{!m||a==="unifiedCanvas"&&m.base_model==="sdxl"||h.push({value:v,label:m.model_name,group:vr[m.base_model]})}),h},[o,a]),d=f.useMemo(()=>(o==null?void 0:o.entities[`${n==null?void 0:n.base_model}/main/${n==null?void 0:n.model_name}`])??null,[o==null?void 0:o.entities,n]),p=f.useCallback(h=>{if(!h)return;const m=Jm(h);m&&e(hv(m))},[e]);return s?i.jsx(sr,{label:t("modelManager.model"),placeholder:"Loading...",disabled:!0,data:[]}):i.jsxs(H,{w:"100%",alignItems:"center",gap:3,children:[i.jsx(sr,{tooltip:d==null?void 0:d.description,label:t("modelManager.model"),value:d==null?void 0:d.id,placeholder:c.length>0?"Select a model":"No models available",data:c,error:c.length===0,disabled:c.length===0,onChange:p,w:"100%"}),r&&i.jsx(Oe,{mt:7,children:i.jsx(Wd,{iconMode:!0})})]})},Jte=f.memo(Qte),_O=e=>{const t=tm("models"),[n,r,o]=e.split("/"),s=$M.safeParse({base_model:n,model_name:o});if(!s.success){t.error({vaeModelId:e,errors:s.error.format()},"Failed to parse VAE model id");return}return s.data},Zte=fe(Ye,({generation:e})=>{const{model:t,vae:n}=e;return{model:t,vae:n}},Ge),ene=()=>{const e=te(),{t}=be(),{model:n,vae:r}=z(Zte),{data:o}=F_(),s=f.useMemo(()=>{if(!o)return[];const d=[{value:"default",label:"Default",group:"Default"}];return jo(o.entities,(p,h)=>{if(!p)return;const m=(n==null?void 0:n.base_model)!==p.base_model;d.push({value:h,label:p.model_name,group:vr[p.base_model],disabled:m,tooltip:m?`Incompatible base model: ${p.base_model}`:void 0})}),d.sort((p,h)=>p.disabled&&!h.disabled?1:-1)},[o,n==null?void 0:n.base_model]),a=f.useMemo(()=>(o==null?void 0:o.entities[`${r==null?void 0:r.base_model}/vae/${r==null?void 0:r.model_name}`])??null,[o==null?void 0:o.entities,r]),c=f.useCallback(d=>{if(!d||d==="default"){e(Q2(null));return}const p=_O(d);p&&e(Q2(p))},[e]);return i.jsx(sr,{itemComponent:Oi,tooltip:a==null?void 0:a.description,label:t("modelManager.vae"),value:(a==null?void 0:a.id)??"default",placeholder:"Default",data:s,onChange:c,disabled:s.length===0,clearable:!0})},tne=f.memo(ene),Mi=e=>e.generation,nne=fe([La,Mi],(e,t)=>{const{scheduler:n}=t,{favoriteSchedulers:r}=e,o=cs(H1,(s,a)=>({value:a,label:s,group:r.includes(a)?"Favorites":void 0})).sort((s,a)=>s.label.localeCompare(a.label));return{scheduler:n,data:o}},Ge),rne=()=>{const e=te(),{t}=be(),{scheduler:n,data:r}=z(nne),o=f.useCallback(s=>{s&&e(mv(s))},[e]);return i.jsx(sr,{label:t("parameters.scheduler"),value:n,data:r,onChange:o})},one=f.memo(rne),sne=fe(Ye,({generation:e})=>{const{vaePrecision:t}=e;return{vaePrecision:t}},Ge),ane=["fp16","fp32"],ine=()=>{const e=te(),{vaePrecision:t}=z(sne),n=f.useCallback(r=>{r&&e(zM(r))},[e]);return i.jsx(Yr,{label:"VAE Precision",value:t,data:ane,onChange:n})},lne=f.memo(ine),cne=()=>{const e=ar("vae").isFeatureEnabled;return i.jsxs(H,{gap:3,w:"full",flexWrap:e?"wrap":"nowrap",children:[i.jsx(Oe,{w:"full",children:i.jsx(Jte,{})}),i.jsx(Oe,{w:"full",children:i.jsx(one,{})}),e&&i.jsxs(H,{w:"full",gap:3,children:[i.jsx(tne,{}),i.jsx(lne,{})]})]})},Si=f.memo(cne),une=[{name:"Free",value:null},{name:"2:3",value:2/3},{name:"16:9",value:16/9},{name:"1:1",value:1/1}];function PO(){const e=z(o=>o.generation.aspectRatio),t=te(),n=z(o=>o.generation.shouldFitToWidthHeight),r=z(Kn);return i.jsx(H,{gap:2,flexGrow:1,children:i.jsx(nr,{isAttached:!0,children:une.map(o=>i.jsx(rn,{size:"sm",isChecked:e===o.value,isDisabled:r==="img2img"?!n:!1,onClick:()=>t(LM(o.value)),children:o.name},o.name))})})}const dne=fe([Ye],({generation:e,hotkeys:t,config:n})=>{const{initial:r,min:o,sliderMax:s,inputMax:a,fineStep:c,coarseStep:d}=n.sd.height,{height:p}=e,{aspectRatio:h}=e,m=t.shift?c:d;return{height:p,initial:r,min:o,sliderMax:s,inputMax:a,step:m,aspectRatio:h}},Ge),fne=e=>{const{height:t,initial:n,min:r,sliderMax:o,inputMax:s,step:a,aspectRatio:c}=z(dne),d=te(),{t:p}=be(),h=f.useCallback(v=>{if(d(mc(v)),c){const b=Ss(v*c,8);d(hc(b))}},[d,c]),m=f.useCallback(()=>{if(d(mc(n)),c){const v=Ss(n*c,8);d(hc(v))}},[d,n,c]);return i.jsx(_t,{label:p("parameters.height"),value:t,min:r,step:a,max:o,onChange:h,handleReset:m,withInput:!0,withReset:!0,withSliderMarks:!0,sliderNumberInputProps:{max:s},...e})},pne=f.memo(fne),hne=fe([Ye],({generation:e,hotkeys:t,config:n})=>{const{initial:r,min:o,sliderMax:s,inputMax:a,fineStep:c,coarseStep:d}=n.sd.width,{width:p,aspectRatio:h}=e,m=t.shift?c:d;return{width:p,initial:r,min:o,sliderMax:s,inputMax:a,step:m,aspectRatio:h}},Ge),mne=e=>{const{width:t,initial:n,min:r,sliderMax:o,inputMax:s,step:a,aspectRatio:c}=z(hne),d=te(),{t:p}=be(),h=f.useCallback(v=>{if(d(hc(v)),c){const b=Ss(v/c,8);d(mc(b))}},[d,c]),m=f.useCallback(()=>{if(d(hc(n)),c){const v=Ss(n/c,8);d(mc(v))}},[d,n,c]);return i.jsx(_t,{label:p("parameters.width"),value:t,min:r,step:a,max:o,onChange:h,handleReset:m,withInput:!0,withReset:!0,withSliderMarks:!0,sliderNumberInputProps:{max:s},...e})},gne=f.memo(mne);function Ic(){const{t:e}=be(),t=te(),n=z(o=>o.generation.shouldFitToWidthHeight),r=z(Kn);return i.jsxs(H,{sx:{gap:2,p:4,borderRadius:4,flexDirection:"column",w:"full",bg:"base.150",_dark:{bg:"base.750"}},children:[i.jsxs(H,{alignItems:"center",gap:2,children:[i.jsx(tt,{sx:{fontSize:"sm",width:"full",color:"base.700",_dark:{color:"base.300"}},children:e("parameters.aspectRatio")}),i.jsx(fl,{}),i.jsx(PO,{}),i.jsx(Le,{tooltip:e("ui.swapSizes"),"aria-label":e("ui.swapSizes"),size:"sm",icon:i.jsx(sO,{}),fontSize:20,isDisabled:r==="img2img"?!n:!1,onClick:()=>t(BM())})]}),i.jsx(H,{gap:2,alignItems:"center",children:i.jsxs(H,{gap:2,flexDirection:"column",width:"full",children:[i.jsx(gne,{isDisabled:r==="img2img"?!n:!1}),i.jsx(pne,{isDisabled:r==="img2img"?!n:!1})]})})]})}const vne=fe([Ye],({generation:e,config:t,ui:n,hotkeys:r})=>{const{initial:o,min:s,sliderMax:a,inputMax:c,fineStep:d,coarseStep:p}=t.sd.steps,{steps:h}=e,{shouldUseSliders:m}=n,v=r.shift?d:p;return{steps:h,initial:o,min:s,sliderMax:a,inputMax:c,step:v,shouldUseSliders:m}},Ge),bne=()=>{const{steps:e,initial:t,min:n,sliderMax:r,inputMax:o,step:s,shouldUseSliders:a}=z(vne),c=te(),{t:d}=be(),p=f.useCallback(v=>{c(Dp(v))},[c]),h=f.useCallback(()=>{c(Dp(t))},[c,t]),m=f.useCallback(()=>{c(ud())},[c]);return a?i.jsx(_t,{label:d("parameters.steps"),min:n,max:r,step:s,onChange:p,handleReset:h,value:e,withInput:!0,withReset:!0,withSliderMarks:!0,sliderNumberInputProps:{max:o}}):i.jsx(Gc,{label:d("parameters.steps"),min:n,max:o,step:s,onChange:p,value:e,numberInputFieldProps:{textAlign:"center"},onBlur:m})},Ci=f.memo(bne);function jO(){const e=te(),t=z(o=>o.generation.shouldFitToWidthHeight),n=o=>e(FM(o.target.checked)),{t:r}=be();return i.jsx(wr,{label:r("parameters.imageFit"),isChecked:t,onChange:n})}function yne(){const e=z(a=>a.generation.seed),t=z(a=>a.generation.shouldRandomizeSeed),n=z(a=>a.generation.shouldGenerateVariations),{t:r}=be(),o=te(),s=a=>o(Rp(a));return i.jsx(Gc,{label:r("parameters.seed"),step:1,precision:0,flexGrow:1,min:H_,max:W_,isDisabled:t,isInvalid:e<0&&n,onChange:s,value:e})}const xne=(e,t)=>Math.floor(Math.random()*(t-e+1)+e);function wne(){const e=te(),t=z(o=>o.generation.shouldRandomizeSeed),{t:n}=be(),r=()=>e(Rp(xne(H_,W_)));return i.jsx(Le,{size:"sm",isDisabled:t,"aria-label":n("parameters.shuffle"),tooltip:n("parameters.shuffle"),onClick:r,icon:i.jsx(cW,{})})}const Sne=()=>{const e=te(),{t}=be(),n=z(o=>o.generation.shouldRandomizeSeed),r=o=>e(HM(o.target.checked));return i.jsx(wr,{label:t("common.random"),isChecked:n,onChange:r})},Cne=f.memo(Sne),kne=()=>i.jsxs(H,{sx:{gap:3,alignItems:"flex-end"},children:[i.jsx(yne,{}),i.jsx(wne,{}),i.jsx(Cne,{})]}),ki=f.memo(kne),_ne=fe([Ye],({sdxl:e})=>{const{sdxlImg2ImgDenoisingStrength:t}=e;return{sdxlImg2ImgDenoisingStrength:t}},Ge),Pne=()=>{const{sdxlImg2ImgDenoisingStrength:e}=z(_ne),t=te(),{t:n}=be(),r=f.useCallback(s=>t(J2(s)),[t]),o=f.useCallback(()=>{t(J2(.7))},[t]);return i.jsx(_t,{label:`${n("parameters.denoisingStrength")}`,step:.01,min:0,max:1,onChange:r,handleReset:o,value:e,isInteger:!1,withInput:!0,withSliderMarks:!0,withReset:!0})},jne=f.memo(Pne),Ine=fe([La,Mi],(e,t)=>{const{shouldUseSliders:n}=e,{shouldRandomizeSeed:r}=t;return{shouldUseSliders:n,activeLabel:r?void 0:"Manual Seed"}},Ge),Ene=()=>{const{shouldUseSliders:e,activeLabel:t}=z(Ine);return i.jsx(Oo,{label:"General",activeLabel:t,defaultIsOpen:!0,children:i.jsxs(H,{sx:{flexDirection:"column",gap:3},children:[e?i.jsxs(i.Fragment,{children:[i.jsx(wi,{}),i.jsx(Ci,{}),i.jsx(xi,{}),i.jsx(Si,{}),i.jsx(Oe,{pt:2,children:i.jsx(ki,{})}),i.jsx(Ic,{})]}):i.jsxs(i.Fragment,{children:[i.jsxs(H,{gap:3,children:[i.jsx(wi,{}),i.jsx(Ci,{}),i.jsx(xi,{})]}),i.jsx(Si,{}),i.jsx(Oe,{pt:2,children:i.jsx(ki,{})}),i.jsx(Ic,{})]}),i.jsx(jne,{}),i.jsx(jO,{})]})})},One=f.memo(Ene),IO=()=>i.jsxs(i.Fragment,{children:[i.jsxs(H,{sx:{flexDirection:"column",gap:2,p:2,borderRadius:4,bg:"base.100",_dark:{bg:"base.850"}},children:[i.jsx(Fd,{}),i.jsx(CO,{}),i.jsx(Ld,{}),i.jsx(SO,{}),i.jsx(wO,{})]}),i.jsx(Hd,{}),i.jsx(One,{}),i.jsx(kO,{}),i.jsx(zd,{}),i.jsx(Xm,{})]}),EO=e=>{const{sx:t}=e,n=te(),r=z(a=>a.ui.shouldPinParametersPanel),{t:o}=be(),s=()=>{n(WM(!r)),n(So())};return i.jsx(Le,{...e,tooltip:o("common.pinOptionsPanel"),"aria-label":o("common.pinOptionsPanel"),onClick:s,icon:r?i.jsx(ij,{}):i.jsx(lj,{}),variant:"ghost",size:"sm",sx:{color:"base.500",_hover:{color:"base.600"},_active:{color:"base.700"},_dark:{color:"base.500",_hover:{color:"base.400"},_active:{color:"base.300"}},...t}})},Rne=fe(La,e=>{const{shouldPinParametersPanel:t,shouldShowParametersPanel:n}=e;return{shouldPinParametersPanel:t,shouldShowParametersPanel:n}}),Mne=e=>{const{shouldPinParametersPanel:t,shouldShowParametersPanel:n}=z(Rne);return t&&n?i.jsxs(Oe,{sx:{position:"relative",h:"full",w:$y,flexShrink:0},children:[i.jsx(H,{sx:{gap:2,flexDirection:"column",h:"full",w:"full",position:"absolute",overflowY:"auto"},children:e.children}),i.jsx(EO,{sx:{position:"absolute",top:0,insetInlineEnd:0}})]}):null},Ly=f.memo(Mne),Dne=e=>{const{direction:t="horizontal",...n}=e,{colorMode:r}=Ds();return t==="horizontal"?i.jsx(w1,{children:i.jsx(H,{sx:{w:6,h:"full",justifyContent:"center",alignItems:"center"},...n,children:i.jsx(Oe,{sx:{w:.5,h:"calc(100% - 4px)",bg:ze("base.100","base.850")(r)}})})}):i.jsx(w1,{children:i.jsx(H,{sx:{w:"full",h:6,justifyContent:"center",alignItems:"center"},...n,children:i.jsx(Oe,{sx:{w:"calc(100% - 4px)",h:.5,bg:ze("base.100","base.850")(r)}})})})},OO=f.memo(Dne),Tne=fe([Ye],({system:e})=>{const{isProcessing:t,isConnected:n}=e;return n&&!t}),Ane=e=>{const{onClick:t,isDisabled:n}=e,{t:r}=be(),o=z(Tne);return i.jsx(Le,{onClick:t,icon:i.jsx(us,{}),tooltip:`${r("gallery.deleteImage")} (Del)`,"aria-label":`${r("gallery.deleteImage")} (Del)`,isDisabled:n||!o,colorScheme:"error"})},Nne=[{label:"RealESRGAN x2 Plus",value:"RealESRGAN_x2plus.pth",tooltip:"Attempts to retain sharpness, low smoothing",group:"x2 Upscalers"},{label:"RealESRGAN x4 Plus",value:"RealESRGAN_x4plus.pth",tooltip:"Best for photos and highly detailed images, medium smoothing",group:"x4 Upscalers"},{label:"RealESRGAN x4 Plus (anime 6B)",value:"RealESRGAN_x4plus_anime_6B.pth",tooltip:"Best for anime/manga, high smoothing",group:"x4 Upscalers"},{label:"ESRGAN SRx4",value:"ESRGAN_SRx4_DF2KOST_official-ff704c30.pth",tooltip:"Retains sharpness, low smoothing",group:"x4 Upscalers"}];function $ne(){const e=z(r=>r.postprocessing.esrganModelName),t=te(),n=r=>t(VM(r));return i.jsx(Yr,{label:"ESRGAN Model",value:e,itemComponent:Oi,onChange:n,data:Nne})}const zne=e=>{const{imageDTO:t}=e,n=te(),r=z(jr),{t:o}=be(),{isOpen:s,onOpen:a,onClose:c}=ss(),d=f.useCallback(()=>{c(),t&&n(V_({image_name:t.image_name}))},[n,t,c]);return i.jsx(gl,{isOpen:s,onClose:c,triggerComponent:i.jsx(Le,{onClick:a,icon:i.jsx(KH,{}),"aria-label":o("parameters.upscale")}),children:i.jsxs(H,{sx:{flexDirection:"column",gap:4},children:[i.jsx($ne,{}),i.jsx(rn,{size:"sm",isDisabled:!t||r,onClick:d,children:o("parameters.upscaleImage")})]})})},Lne=fe([Ye,Kn],({gallery:e,system:t,ui:n},r)=>{const{isProcessing:o,isConnected:s,shouldConfirmOnDelete:a,progressImage:c}=t,{shouldShowImageDetails:d,shouldHidePreview:p,shouldShowProgressInViewer:h}=n,m=e.selection[e.selection.length-1];return{canDeleteImage:s&&!o,shouldConfirmOnDelete:a,isProcessing:o,isConnected:s,shouldDisableToolbarButtons:!!c||!m,shouldShowImageDetails:d,activeTabName:r,shouldHidePreview:p,shouldShowProgressInViewer:h,lastSelectedImage:m}},{memoizeOptions:{resultEqualityCheck:Qt}}),Bne=e=>{const t=te(),{isProcessing:n,isConnected:r,shouldDisableToolbarButtons:o,shouldShowImageDetails:s,lastSelectedImage:a,shouldShowProgressInViewer:c}=z(Lne),d=ar("upscaling").isFeatureEnabled,p=Bc(),{t:h}=be(),{recallBothPrompts:m,recallSeed:v,recallAllParameters:b}=Ey(),[w,y]=Ry(a,500),{currentData:S}=os(a??oo.skipToken),{currentData:k}=L1(y.isPending()?oo.skipToken:w??oo.skipToken),_=k==null?void 0:k.metadata,I=f.useCallback(()=>{b(_)},[_,b]);nt("a",()=>{},[_,b]);const P=f.useCallback(()=>{v(_==null?void 0:_.seed)},[_==null?void 0:_.seed,v]);nt("s",P,[S]);const E=f.useCallback(()=>{m(_==null?void 0:_.positive_prompt,_==null?void 0:_.negative_prompt)},[_==null?void 0:_.negative_prompt,_==null?void 0:_.positive_prompt,m]);nt("p",E,[S]);const O=f.useCallback(()=>{t(XE()),t($1(S))},[t,S]);nt("shift+i",O,[S]);const R=f.useCallback(()=>{S&&t(V_({image_name:S.image_name}))},[t,S]),M=f.useCallback(()=>{S&&t(B1(S))},[t,S]);nt("Shift+U",()=>{R()},{enabled:()=>!!(d&&!o&&r&&!n)},[d,S,o,r,n]);const T=f.useCallback(()=>t(UM(!s)),[t,s]);nt("i",()=>{S?T():p({title:h("toast.metadataLoadFailed"),status:"error",duration:2500,isClosable:!0})},[S,s,p]),nt("delete",()=>{M()},[t,S]);const A=f.useCallback(()=>{t(B_(!c))},[t,c]);return i.jsx(i.Fragment,{children:i.jsxs(H,{sx:{flexWrap:"wrap",justifyContent:"center",alignItems:"center",gap:2},...e,children:[i.jsx(nr,{isAttached:!0,isDisabled:o,children:i.jsxs(kd,{children:[i.jsx(_d,{as:Le,"aria-label":`${h("parameters.sendTo")}...`,tooltip:`${h("parameters.sendTo")}...`,isDisabled:!S,icon:i.jsx(pW,{})}),i.jsx(zc,{motionProps:nm,children:S&&i.jsx(QE,{imageDTO:S})})]})}),i.jsxs(nr,{isAttached:!0,isDisabled:o,children:[i.jsx(Le,{icon:i.jsx(x6,{}),tooltip:`${h("parameters.usePrompt")} (P)`,"aria-label":`${h("parameters.usePrompt")} (P)`,isDisabled:!(_!=null&&_.positive_prompt),onClick:E}),i.jsx(Le,{icon:i.jsx(w6,{}),tooltip:`${h("parameters.useSeed")} (S)`,"aria-label":`${h("parameters.useSeed")} (S)`,isDisabled:!(_!=null&&_.seed),onClick:P}),i.jsx(Le,{icon:i.jsx(d6,{}),tooltip:`${h("parameters.useAll")} (A)`,"aria-label":`${h("parameters.useAll")} (A)`,isDisabled:!_,onClick:I})]}),d&&i.jsx(nr,{isAttached:!0,isDisabled:o,children:d&&i.jsx(zne,{imageDTO:S})}),i.jsx(nr,{isAttached:!0,isDisabled:o,children:i.jsx(Le,{icon:i.jsx(Lb,{}),tooltip:`${h("parameters.info")} (I)`,"aria-label":`${h("parameters.info")} (I)`,isChecked:s,onClick:T})}),i.jsx(nr,{isAttached:!0,children:i.jsx(Le,{"aria-label":h("settings.displayInProgress"),tooltip:h("settings.displayInProgress"),icon:i.jsx(eW,{}),isChecked:c,onClick:A})}),i.jsx(nr,{isAttached:!0,children:i.jsx(Ane,{onClick:M,isDisabled:o})})]})})},Fne=fe([Ye,A_],(e,t)=>{var k,_;const{data:n,status:r}=GM.endpoints.listImages.select(t)(e),o=e.gallery.selection[e.gallery.selection.length-1],s=r==="pending";if(!n||!o||n.total===0)return{isFetching:s,queryArgs:t,isOnFirstImage:!0,isOnLastImage:!0};const a={...t,offset:n.ids.length,limit:$_},c=qM.getSelectors(),d=c.selectAll(n),p=d.findIndex(I=>I.image_name===o),h=Es(p+1,0,d.length-1),m=Es(p-1,0,d.length-1),v=(k=d[h])==null?void 0:k.image_name,b=(_=d[m])==null?void 0:_.image_name,w=c.selectById(n,v),y=c.selectById(n,b),S=d.length;return{isOnFirstImage:p===0,isOnLastImage:!isNaN(p)&&p===S-1,areMoreImagesAvailable:((n==null?void 0:n.total)??0)>S,isFetching:r==="pending",nextImage:w,prevImage:y,nextImageId:v,prevImageId:b,queryArgs:a}},{memoizeOptions:{resultEqualityCheck:Qt}}),RO=()=>{const e=te(),{isOnFirstImage:t,isOnLastImage:n,nextImageId:r,prevImageId:o,areMoreImagesAvailable:s,isFetching:a,queryArgs:c}=z(Fne),d=f.useCallback(()=>{o&&e(gv(o))},[e,o]),p=f.useCallback(()=>{r&&e(gv(r))},[e,r]),[h]=N_(),m=f.useCallback(()=>{h(c)},[h,c]);return{handlePrevImage:d,handleNextImage:p,isOnFirstImage:t,isOnLastImage:n,nextImageId:r,prevImageId:o,areMoreImagesAvailable:s,handleLoadMoreImages:m,isFetching:a}};function Hne(e){return rt({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M245.09 327.74v-37.32c57.07 0 84.51 13.47 108.58 38.68 5.4 5.65 15 1.32 14.29-6.43-5.45-61.45-34.14-117.09-122.87-117.09v-37.32a8.32 8.32 0 00-14.05-6L146.58 242a8.2 8.2 0 000 11.94L231 333.71a8.32 8.32 0 0014.09-5.97z"}},{tag:"path",attr:{fill:"none",strokeMiterlimit:"10",strokeWidth:"32",d:"M256 64C150 64 64 150 64 256s86 192 192 192 192-86 192-192S362 64 256 64z"}}]})(e)}const ys=({label:e,value:t,onClick:n,isLink:r,labelPosition:o,withCopy:s=!1})=>{const{t:a}=be();return t?i.jsxs(H,{gap:2,children:[n&&i.jsx(wn,{label:`Recall ${e}`,children:i.jsx(Sa,{"aria-label":a("accessibility.useThisParameter"),icon:i.jsx(Hne,{}),size:"xs",variant:"ghost",fontSize:20,onClick:n})}),s&&i.jsx(wn,{label:`Copy ${e}`,children:i.jsx(Sa,{"aria-label":`Copy ${e}`,icon:i.jsx(Fc,{}),size:"xs",variant:"ghost",fontSize:14,onClick:()=>navigator.clipboard.writeText(t.toString())})}),i.jsxs(H,{direction:o?"column":"row",children:[i.jsxs(tt,{fontWeight:"semibold",whiteSpace:"pre-wrap",pr:2,children:[e,":"]}),r?i.jsxs(mb,{href:t.toString(),isExternal:!0,wordBreak:"break-all",children:[t.toString()," ",i.jsx(nj,{mx:"2px"})]}):i.jsx(tt,{overflowY:"scroll",wordBreak:"break-all",children:t.toString()})]})]}):null},Wne=e=>{const{metadata:t}=e,{recallPositivePrompt:n,recallNegativePrompt:r,recallSeed:o,recallCfgScale:s,recallModel:a,recallScheduler:c,recallSteps:d,recallWidth:p,recallHeight:h,recallStrength:m}=Ey(),v=f.useCallback(()=>{n(t==null?void 0:t.positive_prompt)},[t==null?void 0:t.positive_prompt,n]),b=f.useCallback(()=>{r(t==null?void 0:t.negative_prompt)},[t==null?void 0:t.negative_prompt,r]),w=f.useCallback(()=>{o(t==null?void 0:t.seed)},[t==null?void 0:t.seed,o]),y=f.useCallback(()=>{a(t==null?void 0:t.model)},[t==null?void 0:t.model,a]),S=f.useCallback(()=>{p(t==null?void 0:t.width)},[t==null?void 0:t.width,p]),k=f.useCallback(()=>{h(t==null?void 0:t.height)},[t==null?void 0:t.height,h]),_=f.useCallback(()=>{c(t==null?void 0:t.scheduler)},[t==null?void 0:t.scheduler,c]),I=f.useCallback(()=>{d(t==null?void 0:t.steps)},[t==null?void 0:t.steps,d]),P=f.useCallback(()=>{s(t==null?void 0:t.cfg_scale)},[t==null?void 0:t.cfg_scale,s]),E=f.useCallback(()=>{m(t==null?void 0:t.strength)},[t==null?void 0:t.strength,m]);return!t||Object.keys(t).length===0?null:i.jsxs(i.Fragment,{children:[t.generation_mode&&i.jsx(ys,{label:"Generation Mode",value:t.generation_mode}),t.positive_prompt&&i.jsx(ys,{label:"Positive Prompt",labelPosition:"top",value:t.positive_prompt,onClick:v}),t.negative_prompt&&i.jsx(ys,{label:"Negative Prompt",labelPosition:"top",value:t.negative_prompt,onClick:b}),t.seed!==void 0&&i.jsx(ys,{label:"Seed",value:t.seed,onClick:w}),t.model!==void 0&&i.jsx(ys,{label:"Model",value:t.model.model_name,onClick:y}),t.width&&i.jsx(ys,{label:"Width",value:t.width,onClick:S}),t.height&&i.jsx(ys,{label:"Height",value:t.height,onClick:k}),t.scheduler&&i.jsx(ys,{label:"Scheduler",value:t.scheduler,onClick:_}),t.steps&&i.jsx(ys,{label:"Steps",value:t.steps,onClick:I}),t.cfg_scale!==void 0&&i.jsx(ys,{label:"CFG scale",value:t.cfg_scale,onClick:P}),t.strength&&i.jsx(ys,{label:"Image to image strength",value:t.strength,onClick:E})]})},Vne=e=>{const{copyTooltip:t,jsonObject:n}=e,r=f.useMemo(()=>JSON.stringify(n,null,2),[n]);return i.jsxs(H,{sx:{borderRadius:"base",bg:"whiteAlpha.500",_dark:{bg:"blackAlpha.500"},flexGrow:1,w:"full",h:"full",position:"relative"},children:[i.jsx(Oe,{sx:{position:"absolute",top:0,left:0,right:0,bottom:0,overflow:"auto",p:4},children:i.jsx(Q6,{defer:!0,style:{height:"100%",width:"100%"},options:{scrollbars:{visibility:"auto",autoHide:"move",autoHideDelay:1300,theme:"os-theme-dark"}},children:i.jsx("pre",{children:r})})}),i.jsx(H,{sx:{position:"absolute",top:0,insetInlineEnd:0,p:2},children:i.jsx(wn,{label:t,children:i.jsx(Sa,{"aria-label":t,icon:i.jsx(Fc,{}),variant:"ghost",onClick:()=>navigator.clipboard.writeText(r)})})})]})},Une=({image:e})=>{const[t,n]=Ry(e.image_name,500),{currentData:r}=L1(n.isPending()?oo.skipToken:t??oo.skipToken),o=r==null?void 0:r.metadata,s=r==null?void 0:r.graph,a=f.useMemo(()=>{const c=[];return o&&c.push({label:"Core Metadata",data:o,copyTooltip:"Copy Core Metadata JSON"}),e&&c.push({label:"Image Details",data:e,copyTooltip:"Copy Image Details JSON"}),s&&c.push({label:"Graph",data:s,copyTooltip:"Copy Graph JSON"}),c},[o,s,e]);return i.jsxs(H,{sx:{padding:4,gap:1,flexDirection:"column",width:"full",height:"full",backdropFilter:"blur(20px)",bg:"baseAlpha.200",_dark:{bg:"blackAlpha.600"},borderRadius:"base",position:"absolute",overflow:"hidden"},children:[i.jsxs(H,{gap:2,children:[i.jsx(tt,{fontWeight:"semibold",children:"File:"}),i.jsxs(mb,{href:e.image_url,isExternal:!0,maxW:"calc(100% - 3rem)",children:[e.image_name,i.jsx(nj,{mx:"2px"})]})]}),i.jsx(Wne,{metadata:o}),i.jsxs(Ed,{variant:"line",sx:{display:"flex",flexDir:"column",w:"full",h:"full"},children:[i.jsx(Od,{children:a.map(c=>i.jsx(wc,{sx:{borderTopRadius:"base"},children:i.jsx(tt,{sx:{color:"base.700",_dark:{color:"base.300"}},children:c.label})},c.label))}),i.jsx(km,{sx:{w:"full",h:"full"},children:a.map(c=>i.jsx(Cm,{sx:{w:"full",h:"full",p:0,pt:4},children:i.jsx(Vne,{jsonObject:c.data,copyTooltip:c.copyTooltip})},c.label))})]})]})},Gne=f.memo(Une),nv={color:"base.100",pointerEvents:"auto"},qne=()=>{const{t:e}=be(),{handlePrevImage:t,handleNextImage:n,isOnFirstImage:r,isOnLastImage:o,handleLoadMoreImages:s,areMoreImagesAvailable:a,isFetching:c}=RO();return i.jsxs(Oe,{sx:{position:"relative",height:"100%",width:"100%"},children:[i.jsx(Oe,{sx:{pos:"absolute",top:"50%",transform:"translate(0, -50%)",insetInlineStart:0},children:!r&&i.jsx(Sa,{"aria-label":e("accessibility.previousImage"),icon:i.jsx($H,{size:64}),variant:"unstyled",onClick:t,boxSize:16,sx:nv})}),i.jsxs(Oe,{sx:{pos:"absolute",top:"50%",transform:"translate(0, -50%)",insetInlineEnd:0},children:[!o&&i.jsx(Sa,{"aria-label":e("accessibility.nextImage"),icon:i.jsx(zH,{size:64}),variant:"unstyled",onClick:n,boxSize:16,sx:nv}),o&&a&&!c&&i.jsx(Sa,{"aria-label":e("accessibility.loadMore"),icon:i.jsx(NH,{size:64}),variant:"unstyled",onClick:s,boxSize:16,sx:nv}),o&&a&&c&&i.jsx(H,{sx:{w:16,h:16,alignItems:"center",justifyContent:"center"},children:i.jsx(dl,{opacity:.5,size:"xl"})})]})]})},Kne=f.memo(qne),Yne=fe([Ye,KM],({ui:e,system:t},n)=>{const{shouldShowImageDetails:r,shouldHidePreview:o,shouldShowProgressInViewer:s}=e,{progressImage:a,shouldAntialiasProgressImage:c}=t;return{shouldShowImageDetails:r,shouldHidePreview:o,imageName:n,progressImage:a,shouldShowProgressInViewer:s,shouldAntialiasProgressImage:c}},{memoizeOptions:{resultEqualityCheck:Qt}}),Xne=()=>{const{shouldShowImageDetails:e,imageName:t,progressImage:n,shouldShowProgressInViewer:r,shouldAntialiasProgressImage:o}=z(Yne),{handlePrevImage:s,handleNextImage:a,prevImageId:c,nextImageId:d,isOnLastImage:p,handleLoadMoreImages:h,areMoreImagesAvailable:m,isFetching:v}=RO();nt("left",()=>{s()},[c]),nt("right",()=>{if(p&&m&&!v){h();return}p||a()},[d,p,m,h,v]);const{currentData:b}=os(t??oo.skipToken),w=f.useMemo(()=>{if(b)return{id:"current-image",payloadType:"IMAGE_DTO",payload:{imageDTO:b}}},[b]),y=f.useMemo(()=>({id:"current-image",actionType:"SET_CURRENT_IMAGE"}),[]),[S,k]=f.useState(!1),_=f.useRef(0),I=f.useCallback(()=>{k(!0),window.clearTimeout(_.current)},[]),P=f.useCallback(()=>{_.current=window.setTimeout(()=>{k(!1)},500)},[]);return i.jsxs(H,{onMouseOver:I,onMouseOut:P,sx:{width:"full",height:"full",alignItems:"center",justifyContent:"center",position:"relative"},children:[n&&r?i.jsx(Tc,{src:n.dataURL,width:n.width,height:n.height,draggable:!1,sx:{objectFit:"contain",maxWidth:"full",maxHeight:"full",height:"auto",position:"absolute",borderRadius:"base",imageRendering:o?"auto":"pixelated"}}):i.jsx(yi,{imageDTO:b,droppableData:y,draggableData:w,isUploadDisabled:!0,fitContainer:!0,useThumbailFallback:!0,dropLabel:"Set as Current Image",noContentFallback:i.jsx(mi,{icon:al,label:"No image selected"})}),e&&b&&i.jsx(Oe,{sx:{position:"absolute",top:"0",width:"full",height:"full",borderRadius:"base"},children:i.jsx(Gne,{image:b})}),i.jsx(Fo,{children:!e&&b&&S&&i.jsx(Xr.div,{initial:{opacity:0},animate:{opacity:1,transition:{duration:.1}},exit:{opacity:0,transition:{duration:.1}},style:{position:"absolute",top:"0",width:"100%",height:"100%",pointerEvents:"none"},children:i.jsx(Kne,{})},"nextPrevButtons")})]})},Qne=f.memo(Xne),Jne=()=>i.jsxs(H,{sx:{position:"relative",flexDirection:"column",height:"100%",width:"100%",rowGap:4,alignItems:"center",justifyContent:"center"},children:[i.jsx(Bne,{}),i.jsx(Qne,{})]}),MO=()=>i.jsx(Oe,{layerStyle:"first",sx:{position:"relative",width:"100%",height:"100%",p:4,borderRadius:"base"},children:i.jsx(H,{sx:{width:"100%",height:"100%"},children:i.jsx(Jne,{})})}),Zne=e=>{const t=te(),{lora:n}=e,r=f.useCallback(a=>{t(YM({id:n.id,weight:a}))},[t,n.id]),o=f.useCallback(()=>{t(XM(n.id))},[t,n.id]),s=f.useCallback(()=>{t(QM(n.id))},[t,n.id]);return i.jsxs(H,{sx:{gap:2.5,alignItems:"flex-end"},children:[i.jsx(_t,{label:n.model_name,value:n.weight,onChange:r,min:-1,max:2,step:.01,withInput:!0,withReset:!0,handleReset:o,withSliderMarks:!0,sliderMarks:[-1,0,1,2],sliderNumberInputProps:{min:-50,max:50}}),i.jsx(Le,{size:"sm",onClick:s,tooltip:"Remove LoRA","aria-label":"Remove LoRA",icon:i.jsx(us,{}),colorScheme:"error"})]})},ere=f.memo(Zne),tre=fe(Ye,({lora:e})=>{const{loras:t}=e;return{loras:t}},Ge),nre=()=>{const{loras:e}=z(tre);return i.jsx(i.Fragment,{children:cs(e,t=>i.jsx(ere,{lora:t},t.model_name))})},rre=fe(Ye,({lora:e})=>({loras:e.loras}),Ge),ore=()=>{const e=te(),{loras:t}=z(rre),{data:n}=U_(),r=z(a=>a.generation.model),o=f.useMemo(()=>{if(!n)return[];const a=[];return jo(n.entities,(c,d)=>{if(!c||d in t)return;const p=(r==null?void 0:r.base_model)!==c.base_model;a.push({value:d,label:c.model_name,disabled:p,group:vr[c.base_model],tooltip:p?`Incompatible base model: ${c.base_model}`:void 0})}),a.sort((c,d)=>{var p;return c.label&&d.label&&(p=c.label)!=null&&p.localeCompare(d.label)?1:-1}),a.sort((c,d)=>c.disabled&&!d.disabled?-1:1)},[t,n,r==null?void 0:r.base_model]),s=f.useCallback(a=>{if(!a)return;const c=n==null?void 0:n.entities[a];c&&e(JM(c))},[e,n==null?void 0:n.entities]);return(n==null?void 0:n.ids.length)===0?i.jsx(H,{sx:{justifyContent:"center",p:2},children:i.jsx(tt,{sx:{fontSize:"sm",color:"base.500",_dark:"base.700"},children:"No LoRAs Loaded"})}):i.jsx(sr,{placeholder:o.length===0?"All LoRAs added":"Add LoRA",value:null,data:o,nothingFound:"No matching LoRAs",itemComponent:Oi,disabled:o.length===0,filter:(a,c)=>{var d;return((d=c.label)==null?void 0:d.toLowerCase().includes(a.toLowerCase().trim()))||c.value.toLowerCase().includes(a.toLowerCase().trim())},onChange:s})},sre=fe(Ye,e=>{const t=G_(e.lora.loras);return{activeLabel:t>0?`${t} Active`:void 0}},Ge),are=()=>{const{activeLabel:e}=z(sre);return ar("lora").isFeatureEnabled?i.jsx(Oo,{label:"LoRA",activeLabel:e,children:i.jsxs(H,{sx:{flexDir:"column",gap:2},children:[i.jsx(ore,{}),i.jsx(nre,{})]})}):null},By=f.memo(are);function ire(){const e=z(d=>d.generation.clipSkip),{model:t}=z(d=>d.generation),n=te(),{t:r}=be(),o=f.useCallback(d=>{n(Z2(d))},[n]),s=f.useCallback(()=>{n(Z2(0))},[n]),a=f.useMemo(()=>t?Of[t.base_model].maxClip:Of["sd-1"].maxClip,[t]),c=f.useMemo(()=>t?Of[t.base_model].markers:Of["sd-1"].markers,[t]);return i.jsx(_t,{label:r("parameters.clipSkip"),"aria-label":r("parameters.clipSkip"),min:0,max:a,step:1,value:e,onChange:o,withSliderMarks:!0,sliderMarks:c,withInput:!0,withReset:!0,handleReset:s})}const lre=fe(Ye,e=>({activeLabel:e.generation.clipSkip>0?"Clip Skip":void 0}),Ge);function Fy(){const{activeLabel:e}=z(lre);return z(n=>n.generation.shouldShowAdvancedOptions)?i.jsx(Oo,{label:"Advanced",activeLabel:e,children:i.jsx(H,{sx:{flexDir:"column",gap:2},children:i.jsx(ire,{})})}):null}const DO=e=>{const t=tm("models"),[n,r,o]=e.split("/"),s=ZM.safeParse({base_model:n,model_name:o});if(!s.success){t.error({controlNetModelId:e,errors:s.error.format()},"Failed to parse ControlNet model id");return}return s.data},cre=e=>{const{controlNetId:t}=e,n=te(),r=z(jr),o=f.useMemo(()=>fe(Ye,({generation:v,controlNet:b})=>{var k,_;const{model:w}=v,y=(k=b.controlNets[t])==null?void 0:k.model,S=(_=b.controlNets[t])==null?void 0:_.isEnabled;return{mainModel:w,controlNetModel:y,isEnabled:S}},Ge),[t]),{mainModel:s,controlNetModel:a,isEnabled:c}=z(o),{data:d}=U1(),p=f.useMemo(()=>{if(!d)return[];const v=[];return jo(d.entities,(b,w)=>{if(!b)return;const y=(b==null?void 0:b.base_model)!==(s==null?void 0:s.base_model);v.push({value:w,label:b.model_name,group:vr[b.base_model],disabled:y,tooltip:y?`Incompatible base model: ${b.base_model}`:void 0})}),v},[d,s==null?void 0:s.base_model]),h=f.useMemo(()=>(d==null?void 0:d.entities[`${a==null?void 0:a.base_model}/controlnet/${a==null?void 0:a.model_name}`])??null,[a==null?void 0:a.base_model,a==null?void 0:a.model_name,d==null?void 0:d.entities]),m=f.useCallback(v=>{if(!v)return;const b=DO(v);b&&n(q_({controlNetId:t,model:b}))},[t,n]);return i.jsx(sr,{itemComponent:Oi,data:p,error:!h||(s==null?void 0:s.base_model)!==h.base_model,placeholder:"Select a model",value:(h==null?void 0:h.id)??null,onChange:m,disabled:r||!c,tooltip:h==null?void 0:h.description})},ure=f.memo(cre),dre=e=>{const{controlNetId:t}=e,n=te(),r=f.useMemo(()=>fe(Ye,({controlNet:c})=>{const{weight:d,isEnabled:p}=c.controlNets[t];return{weight:d,isEnabled:p}},Ge),[t]),{weight:o,isEnabled:s}=z(r),a=f.useCallback(c=>{n(e7({controlNetId:t,weight:c}))},[t,n]);return i.jsx(_t,{isDisabled:!s,label:"Weight",value:o,onChange:a,min:0,max:2,step:.01,withSliderMarks:!0,sliderMarks:[0,1,2]})},fre=f.memo(dre),pre=e=>{const{height:t,controlNetId:n}=e,r=te(),o=f.useMemo(()=>fe(Ye,({controlNet:E})=>{const{pendingControlImages:O}=E,{controlImage:R,processedControlImage:M,processorType:T,isEnabled:A}=E.controlNets[n];return{controlImageName:R,processedControlImageName:M,processorType:T,isEnabled:A,pendingControlImages:O}},Ge),[n]),{controlImageName:s,processedControlImageName:a,processorType:c,pendingControlImages:d,isEnabled:p}=z(o),[h,m]=f.useState(!1),{currentData:v}=os(s??oo.skipToken),{currentData:b}=os(a??oo.skipToken),w=f.useCallback(()=>{r(t7({controlNetId:n,controlImage:null}))},[n,r]),y=f.useCallback(()=>{m(!0)},[]),S=f.useCallback(()=>{m(!1)},[]),k=f.useMemo(()=>{if(v)return{id:n,payloadType:"IMAGE_DTO",payload:{imageDTO:v}}},[v,n]),_=f.useMemo(()=>({id:n,actionType:"SET_CONTROLNET_IMAGE",context:{controlNetId:n}}),[n]),I=f.useMemo(()=>({type:"SET_CONTROLNET_IMAGE",controlNetId:n}),[n]),P=v&&b&&!h&&!d.includes(n)&&c!=="none";return i.jsxs(H,{onMouseEnter:y,onMouseLeave:S,sx:{position:"relative",w:"full",h:t,alignItems:"center",justifyContent:"center",pointerEvents:p?"auto":"none",opacity:p?1:.5},children:[i.jsx(yi,{draggableData:k,droppableData:_,imageDTO:v,isDropDisabled:P||!p,onClickReset:w,postUploadAction:I,resetTooltip:"Reset Control Image",withResetIcon:!!v}),i.jsx(Oe,{sx:{position:"absolute",top:0,insetInlineStart:0,w:"full",h:"full",opacity:P?1:0,transitionProperty:"common",transitionDuration:"normal",pointerEvents:"none"},children:i.jsx(yi,{draggableData:k,droppableData:_,imageDTO:b,isUploadDisabled:!0,isDropDisabled:!p,onClickReset:w,resetTooltip:"Reset Control Image",withResetIcon:!!v})}),d.includes(n)&&i.jsx(H,{sx:{position:"absolute",top:0,insetInlineStart:0,w:"full",h:"full",alignItems:"center",justifyContent:"center",opacity:.8,borderRadius:"base",bg:"base.400",_dark:{bg:"base.900"}},children:i.jsx(dl,{size:"xl",sx:{color:"base.100",_dark:{color:"base.400"}}})})]})},xk=f.memo(pre),As=()=>{const e=te();return f.useCallback((n,r)=>{e(n7({controlNetId:n,changes:r}))},[e])};function Ns(e){return i.jsx(H,{sx:{flexDirection:"column",gap:2},children:e.children})}const wk=ls.canny_image_processor.default,hre=e=>{const{controlNetId:t,processorNode:n,isEnabled:r}=e,{low_threshold:o,high_threshold:s}=n,a=z(jr),c=As(),d=f.useCallback(v=>{c(t,{low_threshold:v})},[t,c]),p=f.useCallback(()=>{c(t,{low_threshold:wk.low_threshold})},[t,c]),h=f.useCallback(v=>{c(t,{high_threshold:v})},[t,c]),m=f.useCallback(()=>{c(t,{high_threshold:wk.high_threshold})},[t,c]);return i.jsxs(Ns,{children:[i.jsx(_t,{isDisabled:a||!r,label:"Low Threshold",value:o,onChange:d,handleReset:p,withReset:!0,min:0,max:255,withInput:!0,withSliderMarks:!0}),i.jsx(_t,{isDisabled:a||!r,label:"High Threshold",value:s,onChange:h,handleReset:m,withReset:!0,min:0,max:255,withInput:!0,withSliderMarks:!0})]})},mre=f.memo(hre),bu=ls.content_shuffle_image_processor.default,gre=e=>{const{controlNetId:t,processorNode:n,isEnabled:r}=e,{image_resolution:o,detect_resolution:s,w:a,h:c,f:d}=n,p=As(),h=z(jr),m=f.useCallback(E=>{p(t,{detect_resolution:E})},[t,p]),v=f.useCallback(()=>{p(t,{detect_resolution:bu.detect_resolution})},[t,p]),b=f.useCallback(E=>{p(t,{image_resolution:E})},[t,p]),w=f.useCallback(()=>{p(t,{image_resolution:bu.image_resolution})},[t,p]),y=f.useCallback(E=>{p(t,{w:E})},[t,p]),S=f.useCallback(()=>{p(t,{w:bu.w})},[t,p]),k=f.useCallback(E=>{p(t,{h:E})},[t,p]),_=f.useCallback(()=>{p(t,{h:bu.h})},[t,p]),I=f.useCallback(E=>{p(t,{f:E})},[t,p]),P=f.useCallback(()=>{p(t,{f:bu.f})},[t,p]);return i.jsxs(Ns,{children:[i.jsx(_t,{label:"Detect Resolution",value:s,onChange:m,handleReset:v,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:h||!r}),i.jsx(_t,{label:"Image Resolution",value:o,onChange:b,handleReset:w,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:h||!r}),i.jsx(_t,{label:"W",value:a,onChange:y,handleReset:S,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:h||!r}),i.jsx(_t,{label:"H",value:c,onChange:k,handleReset:_,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:h||!r}),i.jsx(_t,{label:"F",value:d,onChange:I,handleReset:P,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:h||!r})]})},vre=f.memo(gre),Sk=ls.hed_image_processor.default,bre=e=>{const{controlNetId:t,processorNode:{detect_resolution:n,image_resolution:r,scribble:o},isEnabled:s}=e,a=z(jr),c=As(),d=f.useCallback(b=>{c(t,{detect_resolution:b})},[t,c]),p=f.useCallback(b=>{c(t,{image_resolution:b})},[t,c]),h=f.useCallback(b=>{c(t,{scribble:b.target.checked})},[t,c]),m=f.useCallback(()=>{c(t,{detect_resolution:Sk.detect_resolution})},[t,c]),v=f.useCallback(()=>{c(t,{image_resolution:Sk.image_resolution})},[t,c]);return i.jsxs(Ns,{children:[i.jsx(_t,{label:"Detect Resolution",value:n,onChange:d,handleReset:m,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:a||!s}),i.jsx(_t,{label:"Image Resolution",value:r,onChange:p,handleReset:v,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:a||!s}),i.jsx(wr,{label:"Scribble",isChecked:o,onChange:h,isDisabled:a||!s})]})},yre=f.memo(bre),Ck=ls.lineart_anime_image_processor.default,xre=e=>{const{controlNetId:t,processorNode:n,isEnabled:r}=e,{image_resolution:o,detect_resolution:s}=n,a=As(),c=z(jr),d=f.useCallback(v=>{a(t,{detect_resolution:v})},[t,a]),p=f.useCallback(v=>{a(t,{image_resolution:v})},[t,a]),h=f.useCallback(()=>{a(t,{detect_resolution:Ck.detect_resolution})},[t,a]),m=f.useCallback(()=>{a(t,{image_resolution:Ck.image_resolution})},[t,a]);return i.jsxs(Ns,{children:[i.jsx(_t,{label:"Detect Resolution",value:s,onChange:d,handleReset:h,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:c||!r}),i.jsx(_t,{label:"Image Resolution",value:o,onChange:p,handleReset:m,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:c||!r})]})},wre=f.memo(xre),kk=ls.lineart_image_processor.default,Sre=e=>{const{controlNetId:t,processorNode:n,isEnabled:r}=e,{image_resolution:o,detect_resolution:s,coarse:a}=n,c=As(),d=z(jr),p=f.useCallback(w=>{c(t,{detect_resolution:w})},[t,c]),h=f.useCallback(w=>{c(t,{image_resolution:w})},[t,c]),m=f.useCallback(()=>{c(t,{detect_resolution:kk.detect_resolution})},[t,c]),v=f.useCallback(()=>{c(t,{image_resolution:kk.image_resolution})},[t,c]),b=f.useCallback(w=>{c(t,{coarse:w.target.checked})},[t,c]);return i.jsxs(Ns,{children:[i.jsx(_t,{label:"Detect Resolution",value:s,onChange:p,handleReset:m,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:d||!r}),i.jsx(_t,{label:"Image Resolution",value:o,onChange:h,handleReset:v,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:d||!r}),i.jsx(wr,{label:"Coarse",isChecked:a,onChange:b,isDisabled:d||!r})]})},Cre=f.memo(Sre),_k=ls.mediapipe_face_processor.default,kre=e=>{const{controlNetId:t,processorNode:n,isEnabled:r}=e,{max_faces:o,min_confidence:s}=n,a=As(),c=z(jr),d=f.useCallback(v=>{a(t,{max_faces:v})},[t,a]),p=f.useCallback(v=>{a(t,{min_confidence:v})},[t,a]),h=f.useCallback(()=>{a(t,{max_faces:_k.max_faces})},[t,a]),m=f.useCallback(()=>{a(t,{min_confidence:_k.min_confidence})},[t,a]);return i.jsxs(Ns,{children:[i.jsx(_t,{label:"Max Faces",value:o,onChange:d,handleReset:h,withReset:!0,min:1,max:20,withInput:!0,withSliderMarks:!0,isDisabled:c||!r}),i.jsx(_t,{label:"Min Confidence",value:s,onChange:p,handleReset:m,withReset:!0,min:0,max:1,step:.01,withInput:!0,withSliderMarks:!0,isDisabled:c||!r})]})},_re=f.memo(kre),Pk=ls.midas_depth_image_processor.default,Pre=e=>{const{controlNetId:t,processorNode:n,isEnabled:r}=e,{a_mult:o,bg_th:s}=n,a=As(),c=z(jr),d=f.useCallback(v=>{a(t,{a_mult:v})},[t,a]),p=f.useCallback(v=>{a(t,{bg_th:v})},[t,a]),h=f.useCallback(()=>{a(t,{a_mult:Pk.a_mult})},[t,a]),m=f.useCallback(()=>{a(t,{bg_th:Pk.bg_th})},[t,a]);return i.jsxs(Ns,{children:[i.jsx(_t,{label:"a_mult",value:o,onChange:d,handleReset:h,withReset:!0,min:0,max:20,step:.01,withInput:!0,withSliderMarks:!0,isDisabled:c||!r}),i.jsx(_t,{label:"bg_th",value:s,onChange:p,handleReset:m,withReset:!0,min:0,max:20,step:.01,withInput:!0,withSliderMarks:!0,isDisabled:c||!r})]})},jre=f.memo(Pre),mp=ls.mlsd_image_processor.default,Ire=e=>{const{controlNetId:t,processorNode:n,isEnabled:r}=e,{image_resolution:o,detect_resolution:s,thr_d:a,thr_v:c}=n,d=As(),p=z(jr),h=f.useCallback(_=>{d(t,{detect_resolution:_})},[t,d]),m=f.useCallback(_=>{d(t,{image_resolution:_})},[t,d]),v=f.useCallback(_=>{d(t,{thr_d:_})},[t,d]),b=f.useCallback(_=>{d(t,{thr_v:_})},[t,d]),w=f.useCallback(()=>{d(t,{detect_resolution:mp.detect_resolution})},[t,d]),y=f.useCallback(()=>{d(t,{image_resolution:mp.image_resolution})},[t,d]),S=f.useCallback(()=>{d(t,{thr_d:mp.thr_d})},[t,d]),k=f.useCallback(()=>{d(t,{thr_v:mp.thr_v})},[t,d]);return i.jsxs(Ns,{children:[i.jsx(_t,{label:"Detect Resolution",value:s,onChange:h,handleReset:w,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:p||!r}),i.jsx(_t,{label:"Image Resolution",value:o,onChange:m,handleReset:y,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:p||!r}),i.jsx(_t,{label:"W",value:a,onChange:v,handleReset:S,withReset:!0,min:0,max:1,step:.01,withInput:!0,withSliderMarks:!0,isDisabled:p||!r}),i.jsx(_t,{label:"H",value:c,onChange:b,handleReset:k,withReset:!0,min:0,max:1,step:.01,withInput:!0,withSliderMarks:!0,isDisabled:p||!r})]})},Ere=f.memo(Ire),jk=ls.normalbae_image_processor.default,Ore=e=>{const{controlNetId:t,processorNode:n,isEnabled:r}=e,{image_resolution:o,detect_resolution:s}=n,a=As(),c=z(jr),d=f.useCallback(v=>{a(t,{detect_resolution:v})},[t,a]),p=f.useCallback(v=>{a(t,{image_resolution:v})},[t,a]),h=f.useCallback(()=>{a(t,{detect_resolution:jk.detect_resolution})},[t,a]),m=f.useCallback(()=>{a(t,{image_resolution:jk.image_resolution})},[t,a]);return i.jsxs(Ns,{children:[i.jsx(_t,{label:"Detect Resolution",value:s,onChange:d,handleReset:h,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:c||!r}),i.jsx(_t,{label:"Image Resolution",value:o,onChange:p,handleReset:m,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:c||!r})]})},Rre=f.memo(Ore),Ik=ls.openpose_image_processor.default,Mre=e=>{const{controlNetId:t,processorNode:n,isEnabled:r}=e,{image_resolution:o,detect_resolution:s,hand_and_face:a}=n,c=As(),d=z(jr),p=f.useCallback(w=>{c(t,{detect_resolution:w})},[t,c]),h=f.useCallback(w=>{c(t,{image_resolution:w})},[t,c]),m=f.useCallback(()=>{c(t,{detect_resolution:Ik.detect_resolution})},[t,c]),v=f.useCallback(()=>{c(t,{image_resolution:Ik.image_resolution})},[t,c]),b=f.useCallback(w=>{c(t,{hand_and_face:w.target.checked})},[t,c]);return i.jsxs(Ns,{children:[i.jsx(_t,{label:"Detect Resolution",value:s,onChange:p,handleReset:m,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:d||!r}),i.jsx(_t,{label:"Image Resolution",value:o,onChange:h,handleReset:v,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:d||!r}),i.jsx(wr,{label:"Hand and Face",isChecked:a,onChange:b,isDisabled:d||!r})]})},Dre=f.memo(Mre),Ek=ls.pidi_image_processor.default,Tre=e=>{const{controlNetId:t,processorNode:n,isEnabled:r}=e,{image_resolution:o,detect_resolution:s,scribble:a,safe:c}=n,d=As(),p=z(jr),h=f.useCallback(S=>{d(t,{detect_resolution:S})},[t,d]),m=f.useCallback(S=>{d(t,{image_resolution:S})},[t,d]),v=f.useCallback(()=>{d(t,{detect_resolution:Ek.detect_resolution})},[t,d]),b=f.useCallback(()=>{d(t,{image_resolution:Ek.image_resolution})},[t,d]),w=f.useCallback(S=>{d(t,{scribble:S.target.checked})},[t,d]),y=f.useCallback(S=>{d(t,{safe:S.target.checked})},[t,d]);return i.jsxs(Ns,{children:[i.jsx(_t,{label:"Detect Resolution",value:s,onChange:h,handleReset:v,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:p||!r}),i.jsx(_t,{label:"Image Resolution",value:o,onChange:m,handleReset:b,withReset:!0,min:0,max:4096,withInput:!0,withSliderMarks:!0,isDisabled:p||!r}),i.jsx(wr,{label:"Scribble",isChecked:a,onChange:w}),i.jsx(wr,{label:"Safe",isChecked:c,onChange:y,isDisabled:p||!r})]})},Are=f.memo(Tre),Nre=e=>null,$re=f.memo(Nre),zre=e=>{const{controlNetId:t}=e,n=f.useMemo(()=>fe(Ye,({controlNet:s})=>{const{isEnabled:a,processorNode:c}=s.controlNets[t];return{isEnabled:a,processorNode:c}},Ge),[t]),{isEnabled:r,processorNode:o}=z(n);return o.type==="canny_image_processor"?i.jsx(mre,{controlNetId:t,processorNode:o,isEnabled:r}):o.type==="hed_image_processor"?i.jsx(yre,{controlNetId:t,processorNode:o,isEnabled:r}):o.type==="lineart_image_processor"?i.jsx(Cre,{controlNetId:t,processorNode:o,isEnabled:r}):o.type==="content_shuffle_image_processor"?i.jsx(vre,{controlNetId:t,processorNode:o,isEnabled:r}):o.type==="lineart_anime_image_processor"?i.jsx(wre,{controlNetId:t,processorNode:o,isEnabled:r}):o.type==="mediapipe_face_processor"?i.jsx(_re,{controlNetId:t,processorNode:o,isEnabled:r}):o.type==="midas_depth_image_processor"?i.jsx(jre,{controlNetId:t,processorNode:o,isEnabled:r}):o.type==="mlsd_image_processor"?i.jsx(Ere,{controlNetId:t,processorNode:o,isEnabled:r}):o.type==="normalbae_image_processor"?i.jsx(Rre,{controlNetId:t,processorNode:o,isEnabled:r}):o.type==="openpose_image_processor"?i.jsx(Dre,{controlNetId:t,processorNode:o,isEnabled:r}):o.type==="pidi_image_processor"?i.jsx(Are,{controlNetId:t,processorNode:o,isEnabled:r}):o.type==="zoe_depth_image_processor"?i.jsx($re,{controlNetId:t,processorNode:o,isEnabled:r}):null},Lre=f.memo(zre),Bre=e=>{const{controlNetId:t}=e,n=te(),r=f.useMemo(()=>fe(Ye,({controlNet:d})=>{const{isEnabled:p,shouldAutoConfig:h}=d.controlNets[t];return{isEnabled:p,shouldAutoConfig:h}},Ge),[t]),{isEnabled:o,shouldAutoConfig:s}=z(r),a=z(jr),c=f.useCallback(()=>{n(r7({controlNetId:t}))},[t,n]);return i.jsx(wr,{label:"Auto configure processor","aria-label":"Auto configure processor",isChecked:s,onChange:c,isDisabled:a||!o})},Fre=f.memo(Bre),Ok=e=>`${Math.round(e*100)}%`,Hre=e=>{const{controlNetId:t}=e,n=te(),r=f.useMemo(()=>fe(Ye,({controlNet:d})=>{const{beginStepPct:p,endStepPct:h,isEnabled:m}=d.controlNets[t];return{beginStepPct:p,endStepPct:h,isEnabled:m}},Ge),[t]),{beginStepPct:o,endStepPct:s,isEnabled:a}=z(r),c=f.useCallback(d=>{n(o7({controlNetId:t,beginStepPct:d[0]})),n(s7({controlNetId:t,endStepPct:d[1]}))},[t,n]);return i.jsxs(ho,{isDisabled:!a,children:[i.jsx(zo,{children:"Begin / End Step Percentage"}),i.jsx(di,{w:"100%",gap:2,alignItems:"center",children:i.jsxs(T5,{"aria-label":["Begin Step %","End Step %"],value:[o,s],onChange:c,min:0,max:1,step:.01,minStepsBetweenThumbs:5,isDisabled:!a,children:[i.jsx(A5,{children:i.jsx(N5,{})}),i.jsx(wn,{label:Ok(o),placement:"top",hasArrow:!0,children:i.jsx(Hv,{index:0})}),i.jsx(wn,{label:Ok(s),placement:"top",hasArrow:!0,children:i.jsx(Hv,{index:1})}),i.jsx(kp,{value:0,sx:{insetInlineStart:"0 !important",insetInlineEnd:"unset !important"},children:"0%"}),i.jsx(kp,{value:.5,sx:{insetInlineStart:"50% !important",transform:"translateX(-50%)"},children:"50%"}),i.jsx(kp,{value:1,sx:{insetInlineStart:"unset !important",insetInlineEnd:"0 !important"},children:"100%"})]})})]})},Wre=f.memo(Hre),Vre=[{label:"Balanced",value:"balanced"},{label:"Prompt",value:"more_prompt"},{label:"Control",value:"more_control"},{label:"Mega Control",value:"unbalanced"}];function Ure(e){const{controlNetId:t}=e,n=te(),r=f.useMemo(()=>fe(Ye,({controlNet:c})=>{const{controlMode:d,isEnabled:p}=c.controlNets[t];return{controlMode:d,isEnabled:p}},Ge),[t]),{controlMode:o,isEnabled:s}=z(r),a=f.useCallback(c=>{n(a7({controlNetId:t,controlMode:c}))},[t,n]);return i.jsx(Yr,{disabled:!s,label:"Control Mode",data:Vre,value:String(o),onChange:a})}const Gre=fe(aO,e=>cs(ls,n=>({value:n.type,label:n.label})).sort((n,r)=>n.value==="none"?-1:r.value==="none"?1:n.label.localeCompare(r.label)).filter(n=>!e.sd.disabledControlNetProcessors.includes(n.value)),Ge),qre=e=>{const t=te(),{controlNetId:n}=e,r=f.useMemo(()=>fe(Ye,({controlNet:p})=>{const{isEnabled:h,processorNode:m}=p.controlNets[n];return{isEnabled:h,processorNode:m}},Ge),[n]),o=z(jr),s=z(Gre),{isEnabled:a,processorNode:c}=z(r),d=f.useCallback(p=>{t(i7({controlNetId:n,processorType:p}))},[n,t]);return i.jsx(sr,{label:"Processor",value:c.type??"canny_image_processor",data:s,onChange:d,disabled:o||!a})},Kre=f.memo(qre),Yre=[{label:"Resize",value:"just_resize"},{label:"Crop",value:"crop_resize"},{label:"Fill",value:"fill_resize"}];function Xre(e){const{controlNetId:t}=e,n=te(),r=f.useMemo(()=>fe(Ye,({controlNet:c})=>{const{resizeMode:d,isEnabled:p}=c.controlNets[t];return{resizeMode:d,isEnabled:p}},Ge),[t]),{resizeMode:o,isEnabled:s}=z(r),a=f.useCallback(c=>{n(l7({controlNetId:t,resizeMode:c}))},[t,n]);return i.jsx(Yr,{disabled:!s,label:"Resize Mode",data:Yre,value:String(o),onChange:a})}const Qre=e=>{const{controlNetId:t}=e,n=te(),r=fe(Ye,({controlNet:m})=>{const{isEnabled:v,shouldAutoConfig:b}=m.controlNets[t];return{isEnabled:v,shouldAutoConfig:b}},Ge),{isEnabled:o,shouldAutoConfig:s}=z(r),[a,c]=nee(!1),d=f.useCallback(()=>{n(c7({controlNetId:t}))},[t,n]),p=f.useCallback(()=>{n(u7({sourceControlNetId:t,newControlNetId:ui()}))},[t,n]),h=f.useCallback(()=>{n(d7({controlNetId:t}))},[t,n]);return i.jsxs(H,{sx:{flexDir:"column",gap:3,p:3,borderRadius:"base",position:"relative",bg:"base.200",_dark:{bg:"base.850"}},children:[i.jsxs(H,{sx:{gap:2,alignItems:"center"},children:[i.jsx(wr,{tooltip:"Toggle this ControlNet","aria-label":"Toggle this ControlNet",isChecked:o,onChange:h}),i.jsx(Oe,{sx:{w:"full",minW:0,opacity:o?1:.5,pointerEvents:o?"auto":"none",transitionProperty:"common",transitionDuration:"0.1s"},children:i.jsx(ure,{controlNetId:t})}),i.jsx(Le,{size:"sm",tooltip:"Duplicate","aria-label":"Duplicate",onClick:p,icon:i.jsx(Fc,{})}),i.jsx(Le,{size:"sm",tooltip:"Delete","aria-label":"Delete",colorScheme:"error",onClick:d,icon:i.jsx(us,{})}),i.jsx(Le,{size:"sm",tooltip:a?"Hide Advanced":"Show Advanced","aria-label":a?"Hide Advanced":"Show Advanced",onClick:c,variant:"ghost",sx:{_hover:{bg:"none"}},icon:i.jsx(ay,{sx:{boxSize:4,color:"base.700",transform:a?"rotate(0deg)":"rotate(180deg)",transitionProperty:"common",transitionDuration:"normal",_dark:{color:"base.300"}}})}),!s&&i.jsx(Oe,{sx:{position:"absolute",w:1.5,h:1.5,borderRadius:"full",top:4,insetInlineEnd:4,bg:"accent.700",_dark:{bg:"accent.400"}}})]}),i.jsxs(H,{sx:{w:"full",flexDirection:"column",gap:3},children:[i.jsxs(H,{sx:{gap:4,w:"full",alignItems:"center"},children:[i.jsxs(H,{sx:{flexDir:"column",gap:3,h:28,w:"full",paddingInlineStart:1,paddingInlineEnd:a?1:0,pb:2,justifyContent:"space-between"},children:[i.jsx(fre,{controlNetId:t}),i.jsx(Wre,{controlNetId:t})]}),!a&&i.jsx(H,{sx:{alignItems:"center",justifyContent:"center",h:28,w:28,aspectRatio:"1/1"},children:i.jsx(xk,{controlNetId:t,height:28})})]}),i.jsxs(H,{sx:{gap:2},children:[i.jsx(Ure,{controlNetId:t}),i.jsx(Xre,{controlNetId:t})]}),i.jsx(Kre,{controlNetId:t})]}),a&&i.jsxs(i.Fragment,{children:[i.jsx(xk,{controlNetId:t,height:"392px"}),i.jsx(Fre,{controlNetId:t}),i.jsx(Lre,{controlNetId:t})]})]})},Jre=f.memo(Qre),Zre=fe(Ye,e=>{const{isEnabled:t}=e.controlNet;return{isEnabled:t}},Ge),eoe=()=>{const{isEnabled:e}=z(Zre),t=te(),n=f.useCallback(()=>{t(f7())},[t]);return i.jsx(wr,{label:"Enable ControlNet",isChecked:e,onChange:n,formControlProps:{width:"100%"}})},toe=fe([Ye],({controlNet:e})=>{const{controlNets:t,isEnabled:n}=e,r=p7(t),o=n&&r.length>0?`${r.length} Active`:void 0;return{controlNetsArray:cs(t),activeLabel:o}},Ge),noe=()=>{const{controlNetsArray:e,activeLabel:t}=z(toe),n=ar("controlNet").isFeatureDisabled,r=te(),{firstModel:o}=U1(void 0,{selectFromResult:a=>{var d,p;return{firstModel:(p=a.data)==null?void 0:p.entities[(d=a.data)==null?void 0:d.ids[0]]}}}),s=f.useCallback(()=>{if(!o)return;const a=ui();r(h7({controlNetId:a})),r(q_({controlNetId:a,model:o}))},[r,o]);return n?null:i.jsx(Oo,{label:"ControlNet",activeLabel:t,children:i.jsxs(H,{sx:{flexDir:"column",gap:3},children:[i.jsxs(H,{gap:2,alignItems:"center",children:[i.jsx(H,{sx:{flexDirection:"column",w:"100%",gap:2,px:4,py:2,borderRadius:4,bg:"base.200",_dark:{bg:"base.850"}},children:i.jsx(eoe,{})}),i.jsx(Le,{tooltip:"Add ControlNet","aria-label":"Add ControlNet",icon:i.jsx(ml,{}),isDisabled:!o,flexGrow:1,size:"md",onClick:s})]}),e.map((a,c)=>i.jsxs(f.Fragment,{children:[c>0&&i.jsx(hl,{}),i.jsx(Jre,{controlNetId:a.controlNetId})]},a.controlNetId))]})})},Hy=f.memo(noe),roe=fe(Mi,e=>{const{seamlessXAxis:t}=e;return{seamlessXAxis:t}},Ge),ooe=()=>{const{t:e}=be(),{seamlessXAxis:t}=z(roe),n=te(),r=f.useCallback(o=>{n(m7(o.target.checked))},[n]);return i.jsx(wr,{label:e("parameters.seamlessXAxis"),"aria-label":e("parameters.seamlessXAxis"),isChecked:t,onChange:r})},soe=f.memo(ooe),aoe=fe(Mi,e=>{const{seamlessYAxis:t}=e;return{seamlessYAxis:t}},Ge),ioe=()=>{const{t:e}=be(),{seamlessYAxis:t}=z(aoe),n=te(),r=f.useCallback(o=>{n(g7(o.target.checked))},[n]);return i.jsx(wr,{label:e("parameters.seamlessYAxis"),"aria-label":e("parameters.seamlessYAxis"),isChecked:t,onChange:r})},loe=f.memo(ioe),coe=(e,t)=>{if(e&&t)return"X & Y";if(e)return"X";if(t)return"Y"},uoe=fe(Mi,e=>{const{seamlessXAxis:t,seamlessYAxis:n}=e;return{activeLabel:coe(t,n)}},Ge),doe=()=>{const{t:e}=be(),{activeLabel:t}=z(uoe);return ar("seamless").isFeatureEnabled?i.jsx(Oo,{label:e("parameters.seamlessTiling"),activeLabel:t,children:i.jsxs(H,{sx:{gap:5},children:[i.jsx(Oe,{flexGrow:1,children:i.jsx(soe,{})}),i.jsx(Oe,{flexGrow:1,children:i.jsx(loe,{})})]})}):null},TO=f.memo(doe);function foe(){const e=z(o=>o.generation.horizontalSymmetrySteps),t=z(o=>o.generation.steps),n=te(),{t:r}=be();return i.jsx(_t,{label:r("parameters.hSymmetryStep"),value:e,onChange:o=>n(ew(o)),min:0,max:t,step:1,withInput:!0,withSliderMarks:!0,withReset:!0,handleReset:()=>n(ew(0))})}function poe(){const e=z(o=>o.generation.verticalSymmetrySteps),t=z(o=>o.generation.steps),n=te(),{t:r}=be();return i.jsx(_t,{label:r("parameters.vSymmetryStep"),value:e,onChange:o=>n(tw(o)),min:0,max:t,step:1,withInput:!0,withSliderMarks:!0,withReset:!0,handleReset:()=>n(tw(0))})}function hoe(){const e=z(n=>n.generation.shouldUseSymmetry),t=te();return i.jsx(wr,{label:"Enable Symmetry",isChecked:e,onChange:n=>t(v7(n.target.checked))})}const moe=fe(Ye,e=>({activeLabel:e.generation.shouldUseSymmetry?"Enabled":void 0}),Ge),goe=()=>{const{t:e}=be(),{activeLabel:t}=z(moe);return ar("symmetry").isFeatureEnabled?i.jsx(Oo,{label:e("parameters.symmetry"),activeLabel:t,children:i.jsxs(H,{sx:{gap:2,flexDirection:"column"},children:[i.jsx(hoe,{}),i.jsx(foe,{}),i.jsx(poe,{})]})}):null},Wy=f.memo(goe),voe=fe([Ye],({generation:e,hotkeys:t,config:n})=>{const{initial:r,min:o,sliderMax:s,inputMax:a,fineStep:c,coarseStep:d}=n.sd.img2imgStrength,{img2imgStrength:p}=e,h=t.shift?c:d;return{img2imgStrength:p,initial:r,min:o,sliderMax:s,inputMax:a,step:h}},Ge),boe=()=>{const{img2imgStrength:e,initial:t,min:n,sliderMax:r,inputMax:o,step:s}=z(voe),a=te(),{t:c}=be(),d=f.useCallback(h=>a(Tp(h)),[a]),p=f.useCallback(()=>{a(Tp(t))},[a,t]);return i.jsx(_t,{label:`${c("parameters.denoisingStrength")}`,step:s,min:n,max:r,onChange:d,handleReset:p,value:e,isInteger:!1,withInput:!0,withSliderMarks:!0,withReset:!0,sliderNumberInputProps:{max:o}})},AO=f.memo(boe),yoe=fe([La,Mi],(e,t)=>{const{shouldUseSliders:n}=e,{shouldRandomizeSeed:r}=t;return{shouldUseSliders:n,activeLabel:r?void 0:"Manual Seed"}},Ge),xoe=()=>{const{shouldUseSliders:e,activeLabel:t}=z(yoe);return i.jsx(Oo,{label:"General",activeLabel:t,defaultIsOpen:!0,children:i.jsxs(H,{sx:{flexDirection:"column",gap:3},children:[e?i.jsxs(i.Fragment,{children:[i.jsx(wi,{}),i.jsx(Ci,{}),i.jsx(xi,{}),i.jsx(Si,{}),i.jsx(Oe,{pt:2,children:i.jsx(ki,{})}),i.jsx(Ic,{})]}):i.jsxs(i.Fragment,{children:[i.jsxs(H,{gap:3,children:[i.jsx(wi,{}),i.jsx(Ci,{}),i.jsx(xi,{})]}),i.jsx(Si,{}),i.jsx(Oe,{pt:2,children:i.jsx(ki,{})}),i.jsx(Ic,{})]}),i.jsx(AO,{}),i.jsx(jO,{})]})})},woe=f.memo(xoe),NO=()=>i.jsxs(i.Fragment,{children:[i.jsx(Fd,{}),i.jsx(Ld,{}),i.jsx(Hd,{}),i.jsx(woe,{}),i.jsx(Hy,{}),i.jsx(By,{}),i.jsx(zd,{}),i.jsx(Xm,{}),i.jsx(Wy,{}),i.jsx(TO,{}),i.jsx(Fy,{})]}),Soe=()=>{const e=te(),t=f.useRef(null),n=z(o=>o.generation.model),r=f.useCallback(()=>{t.current&&t.current.setLayout([50,50])},[]);return i.jsxs(H,{sx:{gap:4,w:"full",h:"full"},children:[i.jsx(Ly,{children:n&&n.base_model==="sdxl"?i.jsx(IO,{}):i.jsx(NO,{})}),i.jsx(Oe,{sx:{w:"full",h:"full"},children:i.jsxs(Ay,{ref:t,autoSaveId:"imageTab.content",direction:"horizontal",style:{height:"100%",width:"100%"},children:[i.jsx(sd,{id:"imageTab.content.initImage",order:0,defaultSize:50,minSize:25,style:{position:"relative"},children:i.jsx(Xee,{})}),i.jsx(OO,{onDoubleClick:r}),i.jsx(sd,{id:"imageTab.content.selectedImage",order:1,defaultSize:50,minSize:25,onResize:()=>{e(So())},children:i.jsx(MO,{})})]})})]})},Coe=f.memo(Soe);var koe=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!e(t[o],n[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(s=Object.keys(t),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var a=s[o];if(!e(t[a],n[a]))return!1}return!0}return t!==t&&n!==n};const Rk=cd(koe);function S1(e){return e===null||typeof e!="object"?{}:Object.keys(e).reduce((t,n)=>{const r=e[n];return r!=null&&r!==!1&&(t[n]=r),t},{})}var _oe=Object.defineProperty,Mk=Object.getOwnPropertySymbols,Poe=Object.prototype.hasOwnProperty,joe=Object.prototype.propertyIsEnumerable,Dk=(e,t,n)=>t in e?_oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ioe=(e,t)=>{for(var n in t||(t={}))Poe.call(t,n)&&Dk(e,n,t[n]);if(Mk)for(var n of Mk(t))joe.call(t,n)&&Dk(e,n,t[n]);return e};function $O(e,t){if(t===null||typeof t!="object")return{};const n=Ioe({},t);return Object.keys(t).forEach(r=>{r.includes(`${String(e)}.`)&&delete n[r]}),n}const Eoe="__MANTINE_FORM_INDEX__";function Tk(e,t){return t?typeof t=="boolean"?t:Array.isArray(t)?t.includes(e.replace(/[.][0-9]/g,`.${Eoe}`)):!1:!1}function Ak(e,t,n){typeof n.value=="object"&&(n.value=Ql(n.value)),!n.enumerable||n.get||n.set||!n.configurable||!n.writable||t==="__proto__"?Object.defineProperty(e,t,n):e[t]=n.value}function Ql(e){if(typeof e!="object")return e;var t=0,n,r,o,s=Object.prototype.toString.call(e);if(s==="[object Object]"?o=Object.create(e.__proto__||null):s==="[object Array]"?o=Array(e.length):s==="[object Set]"?(o=new Set,e.forEach(function(a){o.add(Ql(a))})):s==="[object Map]"?(o=new Map,e.forEach(function(a,c){o.set(Ql(c),Ql(a))})):s==="[object Date]"?o=new Date(+e):s==="[object RegExp]"?o=new RegExp(e.source,e.flags):s==="[object DataView]"?o=new e.constructor(Ql(e.buffer)):s==="[object ArrayBuffer]"?o=e.slice(0):s.slice(-6)==="Array]"&&(o=new e.constructor(e)),o){for(r=Object.getOwnPropertySymbols(e);t0,errors:t}}function C1(e,t,n="",r={}){return typeof e!="object"||e===null?r:Object.keys(e).reduce((o,s)=>{const a=e[s],c=`${n===""?"":`${n}.`}${s}`,d=ya(c,t);let p=!1;return typeof a=="function"&&(o[c]=a(d,t,c)),typeof a=="object"&&Array.isArray(d)&&(p=!0,d.forEach((h,m)=>C1(a,t,`${c}.${m}`,o))),typeof a=="object"&&typeof d=="object"&&d!==null&&(p||C1(a,t,c,o)),o},r)}function k1(e,t){return Nk(typeof e=="function"?e(t):C1(e,t))}function gp(e,t,n){if(typeof e!="string")return{hasError:!1,error:null};const r=k1(t,n),o=Object.keys(r.errors).find(s=>e.split(".").every((a,c)=>a===s.split(".")[c]));return{hasError:!!o,error:o?r.errors[o]:null}}function Ooe(e,{from:t,to:n},r){const o=ya(e,r);if(!Array.isArray(o))return r;const s=[...o],a=o[t];return s.splice(t,1),s.splice(n,0,a),Zm(e,s,r)}var Roe=Object.defineProperty,$k=Object.getOwnPropertySymbols,Moe=Object.prototype.hasOwnProperty,Doe=Object.prototype.propertyIsEnumerable,zk=(e,t,n)=>t in e?Roe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Toe=(e,t)=>{for(var n in t||(t={}))Moe.call(t,n)&&zk(e,n,t[n]);if($k)for(var n of $k(t))Doe.call(t,n)&&zk(e,n,t[n]);return e};function Aoe(e,{from:t,to:n},r){const o=`${e}.${t}`,s=`${e}.${n}`,a=Toe({},r);return Object.keys(r).every(c=>{let d,p;if(c.startsWith(o)&&(d=c,p=c.replace(o,s)),c.startsWith(s)&&(d=c.replace(s,o),p=c),d&&p){const h=a[d],m=a[p];return m===void 0?delete a[d]:a[d]=m,h===void 0?delete a[p]:a[p]=h,!1}return!0}),a}function Noe(e,t,n){const r=ya(e,n);return Array.isArray(r)?Zm(e,r.filter((o,s)=>s!==t),n):n}var $oe=Object.defineProperty,Lk=Object.getOwnPropertySymbols,zoe=Object.prototype.hasOwnProperty,Loe=Object.prototype.propertyIsEnumerable,Bk=(e,t,n)=>t in e?$oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Boe=(e,t)=>{for(var n in t||(t={}))zoe.call(t,n)&&Bk(e,n,t[n]);if(Lk)for(var n of Lk(t))Loe.call(t,n)&&Bk(e,n,t[n]);return e};function Fk(e,t){const n=e.substring(t.length+1).split(".")[0];return parseInt(n,10)}function Hk(e,t,n,r){if(t===void 0)return n;const o=`${String(e)}`;let s=n;r===-1&&(s=$O(`${o}.${t}`,s));const a=Boe({},s),c=new Set;return Object.entries(s).filter(([d])=>{if(!d.startsWith(`${o}.`))return!1;const p=Fk(d,o);return Number.isNaN(p)?!1:p>=t}).forEach(([d,p])=>{const h=Fk(d,o),m=d.replace(`${o}.${h}`,`${o}.${h+r}`);a[m]=p,c.add(m),c.has(d)||delete a[d]}),a}function Foe(e,t,n,r){const o=ya(e,r);if(!Array.isArray(o))return r;const s=[...o];return s.splice(typeof n=="number"?n:s.length,0,t),Zm(e,s,r)}function Wk(e,t){const n=Object.keys(e);if(typeof t=="string"){const r=n.filter(o=>o.startsWith(`${t}.`));return e[t]||r.some(o=>e[o])||!1}return n.some(r=>e[r])}function Hoe(e){return t=>{if(!t)e(t);else if(typeof t=="function")e(t);else if(typeof t=="object"&&"nativeEvent"in t){const{currentTarget:n}=t;n instanceof HTMLInputElement?n.type==="checkbox"?e(n.checked):e(n.value):(n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement)&&e(n.value)}else e(t)}}var Woe=Object.defineProperty,Voe=Object.defineProperties,Uoe=Object.getOwnPropertyDescriptors,Vk=Object.getOwnPropertySymbols,Goe=Object.prototype.hasOwnProperty,qoe=Object.prototype.propertyIsEnumerable,Uk=(e,t,n)=>t in e?Woe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ti=(e,t)=>{for(var n in t||(t={}))Goe.call(t,n)&&Uk(e,n,t[n]);if(Vk)for(var n of Vk(t))qoe.call(t,n)&&Uk(e,n,t[n]);return e},rv=(e,t)=>Voe(e,Uoe(t));function qc({initialValues:e={},initialErrors:t={},initialDirty:n={},initialTouched:r={},clearInputErrorOnChange:o=!0,validateInputOnChange:s=!1,validateInputOnBlur:a=!1,transformValues:c=p=>p,validate:d}={}){const[p,h]=f.useState(r),[m,v]=f.useState(n),[b,w]=f.useState(e),[y,S]=f.useState(S1(t)),k=f.useRef(e),_=K=>{k.current=K},I=f.useCallback(()=>h({}),[]),P=K=>{const U=K?ti(ti({},b),K):b;_(U),v({})},E=f.useCallback(K=>S(U=>S1(typeof K=="function"?K(U):K)),[]),O=f.useCallback(()=>S({}),[]),R=f.useCallback(()=>{w(e),O(),_(e),v({}),I()},[]),M=f.useCallback((K,U)=>E(se=>rv(ti({},se),{[K]:U})),[]),T=f.useCallback(K=>E(U=>{if(typeof K!="string")return U;const se=ti({},U);return delete se[K],se}),[]),A=f.useCallback(K=>v(U=>{if(typeof K!="string")return U;const se=$O(K,U);return delete se[K],se}),[]),$=f.useCallback((K,U)=>{const se=Tk(K,s);A(K),h(re=>rv(ti({},re),{[K]:!0})),w(re=>{const oe=Zm(K,U,re);if(se){const pe=gp(K,d,oe);pe.hasError?M(K,pe.error):T(K)}return oe}),!se&&o&&M(K,null)},[]),Q=f.useCallback(K=>{w(U=>{const se=typeof K=="function"?K(U):K;return ti(ti({},U),se)}),o&&O()},[]),B=f.useCallback((K,U)=>{A(K),w(se=>Ooe(K,U,se)),S(se=>Aoe(K,U,se))},[]),V=f.useCallback((K,U)=>{A(K),w(se=>Noe(K,U,se)),S(se=>Hk(K,U,se,-1))},[]),q=f.useCallback((K,U,se)=>{A(K),w(re=>Foe(K,U,se,re)),S(re=>Hk(K,se,re,1))},[]),G=f.useCallback(()=>{const K=k1(d,b);return S(K.errors),K},[b,d]),D=f.useCallback(K=>{const U=gp(K,d,b);return U.hasError?M(K,U.error):T(K),U},[b,d]),L=(K,{type:U="input",withError:se=!0,withFocus:re=!0}={})=>{const pe={onChange:Hoe(le=>$(K,le))};return se&&(pe.error=y[K]),U==="checkbox"?pe.checked=ya(K,b):pe.value=ya(K,b),re&&(pe.onFocus=()=>h(le=>rv(ti({},le),{[K]:!0})),pe.onBlur=()=>{if(Tk(K,a)){const le=gp(K,d,b);le.hasError?M(K,le.error):T(K)}}),pe},W=(K,U)=>se=>{se==null||se.preventDefault();const re=G();re.hasErrors?U==null||U(re.errors,b,se):K==null||K(c(b),se)},Y=K=>c(K||b),ae=f.useCallback(K=>{K.preventDefault(),R()},[]),ye=K=>{if(K){const se=ya(K,m);if(typeof se=="boolean")return se;const re=ya(K,b),oe=ya(K,k.current);return!Rk(re,oe)}return Object.keys(m).length>0?Wk(m):!Rk(b,k.current)},ue=f.useCallback(K=>Wk(p,K),[p]),X=f.useCallback(K=>K?!gp(K,d,b).hasError:!k1(d,b).hasErrors,[b,d]);return{values:b,errors:y,setValues:Q,setErrors:E,setFieldValue:$,setFieldError:M,clearFieldError:T,clearErrors:O,reset:R,validate:G,validateField:D,reorderListItem:B,removeListItem:V,insertListItem:q,getInputProps:L,onSubmit:W,onReset:ae,isDirty:ye,isTouched:ue,setTouched:h,setDirty:v,resetTouched:I,resetDirty:P,isValid:X,getTransformedValues:Y}}function Tr(e){const{...t}=e,{base50:n,base100:r,base200:o,base300:s,base800:a,base700:c,base900:d,accent500:p,accent300:h}=_y(),{colorMode:m}=Ds();return i.jsx(OE,{styles:()=>({input:{color:ze(d,r)(m),backgroundColor:ze(n,d)(m),borderColor:ze(o,a)(m),borderWidth:2,outline:"none",":focus":{borderColor:ze(h,p)(m)}},label:{color:ze(c,s)(m),fontWeight:"normal",marginBottom:4}}),...t})}const Koe=[{value:"sd-1",label:vr["sd-1"]},{value:"sd-2",label:vr["sd-2"]},{value:"sdxl",label:vr.sdxl},{value:"sdxl-refiner",label:vr["sdxl-refiner"]}];function eg(e){const{...t}=e,{t:n}=be();return i.jsx(Yr,{label:n("modelManager.baseModel"),data:Koe,...t})}function LO(e){const{data:t}=K_(),{...n}=e;return i.jsx(Yr,{label:"Config File",placeholder:"Select A Config File",data:t||[],...n})}const Yoe=[{value:"normal",label:"Normal"},{value:"inpaint",label:"Inpaint"},{value:"depth",label:"Depth"}];function tg(e){const{...t}=e,{t:n}=be();return i.jsx(Yr,{label:n("modelManager.variant"),data:Yoe,...t})}function BO(e){const{t}=be(),n=te(),{model_path:r}=e,o=qc({initialValues:{model_name:r?r.split("\\").splice(-1)[0].split(".")[0]:"",base_model:"sd-1",model_type:"main",path:r||"",description:"",model_format:"checkpoint",error:void 0,vae:"",variant:"normal",config:"configs\\stable-diffusion\\v1-inference.yaml"}}),[s]=Y_(),[a,c]=f.useState(!1),d=p=>{s({body:p}).unwrap().then(h=>{n(Dn(Bn({title:`Model Added: ${p.model_name}`,status:"success"}))),o.reset(),r&&n(fd(null))}).catch(h=>{h&&n(Dn(Bn({title:"Model Add Failed",status:"error"})))})};return i.jsx("form",{onSubmit:o.onSubmit(p=>d(p)),style:{width:"100%"},children:i.jsxs(H,{flexDirection:"column",gap:2,children:[i.jsx(Tr,{label:"Model Name",required:!0,...o.getInputProps("model_name")}),i.jsx(eg,{...o.getInputProps("base_model")}),i.jsx(Tr,{label:"Model Location",required:!0,...o.getInputProps("path")}),i.jsx(Tr,{label:"Description",...o.getInputProps("description")}),i.jsx(Tr,{label:"VAE Location",...o.getInputProps("vae")}),i.jsx(tg,{...o.getInputProps("variant")}),i.jsxs(H,{flexDirection:"column",width:"100%",gap:2,children:[a?i.jsx(Tr,{required:!0,label:"Custom Config File Location",...o.getInputProps("config")}):i.jsx(LO,{required:!0,width:"100%",...o.getInputProps("config")}),i.jsx(Gn,{isChecked:a,onChange:()=>c(!a),label:"Use Custom Config"}),i.jsx(rn,{mt:2,type:"submit",children:t("modelManager.addModel")})]})]})})}function FO(e){const{t}=be(),n=te(),{model_path:r}=e,[o]=Y_(),s=qc({initialValues:{model_name:r?r.split("\\").splice(-1)[0]:"",base_model:"sd-1",model_type:"main",path:r||"",description:"",model_format:"diffusers",error:void 0,vae:"",variant:"normal"}}),a=c=>{o({body:c}).unwrap().then(d=>{n(Dn(Bn({title:`Model Added: ${c.model_name}`,status:"success"}))),s.reset(),r&&n(fd(null))}).catch(d=>{d&&n(Dn(Bn({title:"Model Add Failed",status:"error"})))})};return i.jsx("form",{onSubmit:s.onSubmit(c=>a(c)),style:{width:"100%"},children:i.jsxs(H,{flexDirection:"column",gap:2,children:[i.jsx(Tr,{required:!0,label:"Model Name",...s.getInputProps("model_name")}),i.jsx(eg,{...s.getInputProps("base_model")}),i.jsx(Tr,{required:!0,label:"Model Location",placeholder:"Provide the path to a local folder where your Diffusers Model is stored",...s.getInputProps("path")}),i.jsx(Tr,{label:"Description",...s.getInputProps("description")}),i.jsx(Tr,{label:"VAE Location",...s.getInputProps("vae")}),i.jsx(tg,{...s.getInputProps("variant")}),i.jsx(rn,{mt:2,type:"submit",children:t("modelManager.addModel")})]})})}const HO=[{label:"Diffusers",value:"diffusers"},{label:"Checkpoint / Safetensors",value:"checkpoint"}];function Xoe(){const[e,t]=f.useState("diffusers");return i.jsxs(H,{flexDirection:"column",gap:4,width:"100%",children:[i.jsx(Yr,{label:"Model Type",value:e,data:HO,onChange:n=>{n&&t(n)}}),i.jsxs(H,{sx:{p:4,borderRadius:4,bg:"base.300",_dark:{bg:"base.850"}},children:[e==="diffusers"&&i.jsx(FO,{}),e==="checkpoint"&&i.jsx(BO,{})]})]})}const Qoe=[{label:"None",value:"none"},{label:"v_prediction",value:"v_prediction"},{label:"epsilon",value:"epsilon"},{label:"sample",value:"sample"}];function Joe(){const e=te(),{t}=be(),n=z(c=>c.system.isProcessing),[r,{isLoading:o}]=X_(),s=qc({initialValues:{location:"",prediction_type:void 0}}),a=c=>{const d={location:c.location,prediction_type:c.prediction_type==="none"?void 0:c.prediction_type};r({body:d}).unwrap().then(p=>{e(Dn(Bn({title:"Model Added",status:"success"}))),s.reset()}).catch(p=>{p&&(console.log(p),e(Dn(Bn({title:`${p.data.detail} `,status:"error"}))))})};return i.jsx("form",{onSubmit:s.onSubmit(c=>a(c)),style:{width:"100%"},children:i.jsxs(H,{flexDirection:"column",width:"100%",gap:4,children:[i.jsx(Tr,{label:"Model Location",placeholder:"Provide a path to a local Diffusers model, local checkpoint / safetensors model a HuggingFace Repo ID, or a checkpoint/diffusers model URL.",w:"100%",...s.getInputProps("location")}),i.jsx(Yr,{label:"Prediction Type (for Stable Diffusion 2.x Models only)",data:Qoe,defaultValue:"none",...s.getInputProps("prediction_type")}),i.jsx(rn,{type:"submit",isLoading:o,isDisabled:o||n,children:t("modelManager.addModel")})]})})}function Zoe(){const[e,t]=f.useState("simple");return i.jsxs(H,{flexDirection:"column",width:"100%",overflow:"scroll",maxHeight:window.innerHeight-250,gap:4,children:[i.jsxs(nr,{isAttached:!0,children:[i.jsx(rn,{size:"sm",isChecked:e=="simple",onClick:()=>t("simple"),children:"Simple"}),i.jsx(rn,{size:"sm",isChecked:e=="advanced",onClick:()=>t("advanced"),children:"Advanced"})]}),i.jsxs(H,{sx:{p:4,borderRadius:4,background:"base.200",_dark:{background:"base.800"}},children:[e==="simple"&&i.jsx(Joe,{}),e==="advanced"&&i.jsx(Xoe,{})]})]})}const ese={display:"flex",flexDirection:"row",alignItems:"center",gap:10},tse=e=>{const{label:t="",labelPos:n="top",isDisabled:r=!1,isInvalid:o,formControlProps:s,...a}=e,c=te(),d=f.useCallback(h=>{h.shiftKey&&c(_o(!0))},[c]),p=f.useCallback(h=>{h.shiftKey||c(_o(!1))},[c]);return i.jsxs(ho,{isInvalid:o,isDisabled:r,...s,style:n==="side"?ese:void 0,children:[t!==""&&i.jsx(zo,{children:t}),i.jsx(yd,{...a,onPaste:Ny,onKeyDown:d,onKeyUp:p})]})},Ec=f.memo(tse);function nse(e){const{...t}=e;return i.jsx(CI,{w:"100%",...t,children:e.children})}function rse(){const e=z(y=>y.modelmanager.searchFolder),[t,n]=f.useState(""),{data:r}=na(Hu),{foundModels:o,alreadyInstalled:s,filteredModels:a}=Q_({search_path:e||""},{selectFromResult:({data:y})=>{const S=JD(r==null?void 0:r.entities),k=cs(S,"path"),_=YD(y,k),I=rT(y,k);return{foundModels:y,alreadyInstalled:Gk(I,t),filteredModels:Gk(_,t)}}}),[c,{isLoading:d}]=X_(),p=te(),{t:h}=be(),m=f.useCallback(y=>{const S=y.currentTarget.id.split("\\").splice(-1)[0];c({body:{location:y.currentTarget.id}}).unwrap().then(k=>{p(Dn(Bn({title:`Added Model: ${S}`,status:"success"})))}).catch(k=>{k&&p(Dn(Bn({title:"Failed To Add Model",status:"error"})))})},[p,c]),v=f.useCallback(y=>{n(y.target.value)},[]),b=({models:y,showActions:S=!0})=>y.map(k=>i.jsxs(H,{sx:{p:4,gap:4,alignItems:"center",borderRadius:4,bg:"base.200",_dark:{bg:"base.800"}},children:[i.jsxs(H,{w:"100%",sx:{flexDirection:"column",minW:"25%"},children:[i.jsx(tt,{sx:{fontWeight:600},children:k.split("\\").slice(-1)[0]}),i.jsx(tt,{sx:{fontSize:"sm",color:"base.600",_dark:{color:"base.400"}},children:k})]}),S?i.jsxs(H,{gap:2,children:[i.jsx(rn,{id:k,onClick:m,isLoading:d,children:"Quick Add"}),i.jsx(rn,{onClick:()=>p(fd(k)),isLoading:d,children:"Advanced"})]}):i.jsx(tt,{sx:{fontWeight:600,p:2,borderRadius:4,color:"accent.50",bg:"accent.400",_dark:{color:"accent.100",bg:"accent.600"}},children:"Installed"})]},k));return(()=>e?!o||o.length===0?i.jsx(H,{sx:{w:"full",h:"full",justifyContent:"center",alignItems:"center",height:96,userSelect:"none",bg:"base.200",_dark:{bg:"base.900"}},children:i.jsx(tt,{variant:"subtext",children:"No Models Found"})}):i.jsxs(H,{sx:{flexDirection:"column",gap:2,w:"100%",minW:"50%"},children:[i.jsx(Ec,{onChange:v,label:h("modelManager.search"),labelPos:"side"}),i.jsxs(H,{p:2,gap:2,children:[i.jsxs(tt,{sx:{fontWeight:600},children:["Models Found: ",o.length]}),i.jsxs(tt,{sx:{fontWeight:600,color:"accent.500",_dark:{color:"accent.200"}},children:["Not Installed: ",a.length]})]}),i.jsx(nse,{offsetScrollbars:!0,children:i.jsxs(H,{gap:2,flexDirection:"column",children:[b({models:a}),b({models:s,showActions:!1})]})})]}):null)()}const Gk=(e,t)=>{const n=[];return jo(e,r=>{if(!r)return null;r.includes(t)&&n.push(r)}),n};function ose(){const e=z(a=>a.modelmanager.advancedAddScanModel),[t,n]=f.useState("diffusers"),[r,o]=f.useState(!0);f.useEffect(()=>{e&&[".ckpt",".safetensors",".pth",".pt"].some(a=>e.endsWith(a))?n("checkpoint"):n("diffusers")},[e,n,r]);const s=te();return e?i.jsxs(Oe,{as:Xr.div,initial:{x:-100,opacity:0},animate:{x:0,opacity:1,transition:{duration:.2}},sx:{display:"flex",flexDirection:"column",minWidth:"40%",maxHeight:window.innerHeight-300,overflow:"scroll",p:4,gap:4,borderRadius:4,bg:"base.200",_dark:{bg:"base.800"}},children:[i.jsxs(H,{justifyContent:"space-between",alignItems:"center",children:[i.jsx(tt,{size:"xl",fontWeight:600,children:r||t==="checkpoint"?"Add Checkpoint Model":"Add Diffusers Model"}),i.jsx(Le,{icon:i.jsx(mW,{}),"aria-label":"Close Advanced",onClick:()=>s(fd(null)),size:"sm"})]}),i.jsx(Yr,{label:"Model Type",value:t,data:HO,onChange:a=>{a&&(n(a),o(a==="checkpoint"))}}),r?i.jsx(BO,{model_path:e},e):i.jsx(FO,{model_path:e},e)]}):null}function sse(){const e=te(),{t}=be(),n=z(c=>c.modelmanager.searchFolder),{refetch:r}=Q_({search_path:n||""}),o=qc({initialValues:{folder:""}}),s=f.useCallback(c=>{e(nw(c.folder))},[e]),a=()=>{r()};return i.jsx("form",{onSubmit:o.onSubmit(c=>s(c)),style:{width:"100%"},children:i.jsxs(H,{sx:{w:"100%",gap:2,borderRadius:4,alignItems:"center"},children:[i.jsxs(H,{w:"100%",alignItems:"center",gap:4,minH:12,children:[i.jsx(tt,{sx:{fontSize:"sm",fontWeight:600,color:"base.700",minW:"max-content",_dark:{color:"base.300"}},children:"Folder"}),n?i.jsx(H,{sx:{w:"100%",p:2,px:4,bg:"base.300",borderRadius:4,fontSize:"sm",fontWeight:"bold",_dark:{bg:"base.700"}},children:n}):i.jsx(Ec,{w:"100%",size:"md",...o.getInputProps("folder")})]}),i.jsxs(H,{gap:2,children:[n?i.jsx(Le,{"aria-label":t("modelManager.scanAgain"),tooltip:t("modelManager.scanAgain"),icon:i.jsx(S6,{}),onClick:a,fontSize:18,size:"sm"}):i.jsx(Le,{"aria-label":t("modelManager.findModels"),tooltip:t("modelManager.findModels"),icon:i.jsx(dW,{}),fontSize:18,size:"sm",type:"submit"}),i.jsx(Le,{"aria-label":t("modelManager.clearCheckpointFolder"),tooltip:t("modelManager.clearCheckpointFolder"),icon:i.jsx(us,{}),size:"sm",onClick:()=>{e(nw(null)),e(fd(null))},isDisabled:!n,colorScheme:"red"})]})]})})}const ase=f.memo(sse);function ise(){return i.jsxs(H,{flexDirection:"column",w:"100%",gap:4,children:[i.jsx(ase,{}),i.jsxs(H,{gap:4,children:[i.jsx(H,{sx:{maxHeight:window.innerHeight-300,overflow:"scroll",gap:4,w:"100%"},children:i.jsx(rse,{})}),i.jsx(ose,{})]})]})}function lse(){const[e,t]=f.useState("add"),{t:n}=be();return i.jsxs(H,{flexDirection:"column",gap:4,children:[i.jsxs(nr,{isAttached:!0,children:[i.jsx(rn,{onClick:()=>t("add"),isChecked:e=="add",size:"sm",width:"100%",children:n("modelManager.addModel")}),i.jsx(rn,{onClick:()=>t("scan"),isChecked:e=="scan",size:"sm",width:"100%",children:n("modelManager.scanForModels")})]}),e=="add"&&i.jsx(Zoe,{}),e=="scan"&&i.jsx(ise,{})]})}const cse=[{label:"Stable Diffusion 1",value:"sd-1"},{label:"Stable Diffusion 2",value:"sd-2"}];function use(){const{t:e}=be(),t=te(),{data:n}=na(Hu),[r,{isLoading:o}]=b7(),[s,a]=f.useState("sd-1"),c=gw(n==null?void 0:n.entities,(D,L)=>(D==null?void 0:D.model_format)==="diffusers"&&(D==null?void 0:D.base_model)==="sd-1"),d=gw(n==null?void 0:n.entities,(D,L)=>(D==null?void 0:D.model_format)==="diffusers"&&(D==null?void 0:D.base_model)==="sd-2"),p=f.useMemo(()=>({"sd-1":c,"sd-2":d}),[c,d]),[h,m]=f.useState(Object.keys(p[s])[0]),[v,b]=f.useState(Object.keys(p[s])[1]),[w,y]=f.useState(null),[S,k]=f.useState(""),[_,I]=f.useState(.5),[P,E]=f.useState("weighted_sum"),[O,R]=f.useState("root"),[M,T]=f.useState(""),[A,$]=f.useState(!1),Q=Object.keys(p[s]).filter(D=>D!==v&&D!==w),B=Object.keys(p[s]).filter(D=>D!==h&&D!==w),V=Object.keys(p[s]).filter(D=>D!==h&&D!==v),q=D=>{a(D),m(null),b(null)},G=()=>{const D=[];let L=[h,v,w];L=L.filter(Y=>Y!==null),L.forEach(Y=>{Y&&D.push(Y==null?void 0:Y.split("/")[2])});const W={model_names:D,merged_model_name:S!==""?S:D.join("-"),alpha:_,interp:P,force:A,merge_dest_directory:O==="root"?void 0:M};r({base_model:s,body:W}).unwrap().then(Y=>{t(Dn(Bn({title:e("modelManager.modelsMerged"),status:"success"})))}).catch(Y=>{Y&&t(Dn(Bn({title:e("modelManager.modelsMergeFailed"),status:"error"})))})};return i.jsxs(H,{flexDirection:"column",rowGap:4,children:[i.jsxs(H,{sx:{flexDirection:"column",rowGap:1},children:[i.jsx(tt,{children:e("modelManager.modelMergeHeaderHelp1")}),i.jsx(tt,{fontSize:"sm",variant:"subtext",children:e("modelManager.modelMergeHeaderHelp2")})]}),i.jsxs(H,{columnGap:4,children:[i.jsx(Yr,{label:"Model Type",w:"100%",data:cse,value:s,onChange:q}),i.jsx(sr,{label:e("modelManager.modelOne"),w:"100%",value:h,placeholder:e("modelManager.selectModel"),data:Q,onChange:D=>m(D)}),i.jsx(sr,{label:e("modelManager.modelTwo"),w:"100%",placeholder:e("modelManager.selectModel"),value:v,data:B,onChange:D=>b(D)}),i.jsx(sr,{label:e("modelManager.modelThree"),data:V,w:"100%",placeholder:e("modelManager.selectModel"),clearable:!0,onChange:D=>{D?(y(D),E("weighted_sum")):(y(null),E("add_difference"))}})]}),i.jsx(Ec,{label:e("modelManager.mergedModelName"),value:S,onChange:D=>k(D.target.value)}),i.jsxs(H,{sx:{flexDirection:"column",padding:4,borderRadius:"base",gap:4,bg:"base.200",_dark:{bg:"base.800"}},children:[i.jsx(_t,{label:e("modelManager.alpha"),min:.01,max:.99,step:.01,value:_,onChange:D=>I(D),withInput:!0,withReset:!0,handleReset:()=>I(.5),withSliderMarks:!0}),i.jsx(tt,{variant:"subtext",fontSize:"sm",children:e("modelManager.modelMergeAlphaHelp")})]}),i.jsxs(H,{sx:{padding:4,borderRadius:"base",gap:4,bg:"base.200",_dark:{bg:"base.800"}},children:[i.jsx(tt,{fontWeight:500,fontSize:"sm",variant:"subtext",children:e("modelManager.interpolationType")}),i.jsx(Gp,{value:P,onChange:D=>E(D),children:i.jsx(H,{columnGap:4,children:w===null?i.jsxs(i.Fragment,{children:[i.jsx(ba,{value:"weighted_sum",children:i.jsx(tt,{fontSize:"sm",children:e("modelManager.weightedSum")})}),i.jsx(ba,{value:"sigmoid",children:i.jsx(tt,{fontSize:"sm",children:e("modelManager.sigmoid")})}),i.jsx(ba,{value:"inv_sigmoid",children:i.jsx(tt,{fontSize:"sm",children:e("modelManager.inverseSigmoid")})})]}):i.jsx(ba,{value:"add_difference",children:i.jsx(wn,{label:e("modelManager.modelMergeInterpAddDifferenceHelp"),children:i.jsx(tt,{fontSize:"sm",children:e("modelManager.addDifference")})})})})})]}),i.jsxs(H,{sx:{flexDirection:"column",padding:4,borderRadius:"base",gap:4,bg:"base.200",_dark:{bg:"base.900"}},children:[i.jsxs(H,{columnGap:4,children:[i.jsx(tt,{fontWeight:"500",fontSize:"sm",variant:"subtext",children:e("modelManager.mergedModelSaveLocation")}),i.jsx(Gp,{value:O,onChange:D=>R(D),children:i.jsxs(H,{columnGap:4,children:[i.jsx(ba,{value:"root",children:i.jsx(tt,{fontSize:"sm",children:e("modelManager.invokeAIFolder")})}),i.jsx(ba,{value:"custom",children:i.jsx(tt,{fontSize:"sm",children:e("modelManager.custom")})})]})})]}),O==="custom"&&i.jsx(Ec,{label:e("modelManager.mergedModelCustomSaveLocation"),value:M,onChange:D=>T(D.target.value)})]}),i.jsx(Gn,{label:e("modelManager.ignoreMismatch"),isChecked:A,onChange:D=>$(D.target.checked),fontWeight:"500"}),i.jsx(rn,{onClick:G,isLoading:o,isDisabled:h===null||v===null,children:e("modelManager.merge")})]})}const dse=Te((e,t)=>{const{t:n}=be(),{acceptButtonText:r=n("common.accept"),acceptCallback:o,cancelButtonText:s=n("common.cancel"),cancelCallback:a,children:c,title:d,triggerComponent:p}=e,{isOpen:h,onOpen:m,onClose:v}=ss(),b=f.useRef(null),w=()=>{o(),v()},y=()=>{a&&a(),v()};return i.jsxs(i.Fragment,{children:[f.cloneElement(p,{onClick:m,ref:t}),i.jsx(Pd,{isOpen:h,leastDestructiveRef:b,onClose:v,isCentered:!0,children:i.jsx(Ma,{children:i.jsxs(jd,{children:[i.jsx(Ra,{fontSize:"lg",fontWeight:"bold",children:d}),i.jsx(Da,{children:c}),i.jsxs(Oa,{children:[i.jsx(rn,{ref:b,onClick:y,children:s}),i.jsx(rn,{colorScheme:"error",onClick:w,ml:3,children:r})]})]})})})]})}),Vy=f.memo(dse);function fse(e){const{model:t}=e,n=te(),{t:r}=be(),[o,{isLoading:s}]=y7(),[a,c]=f.useState("InvokeAIRoot"),[d,p]=f.useState("");f.useEffect(()=>{c("InvokeAIRoot")},[t]);const h=()=>{c("InvokeAIRoot")},m=()=>{const v={base_model:t.base_model,model_name:t.model_name,params:{convert_dest_directory:a==="Custom"?d:void 0}};if(a==="Custom"&&d===""){n(Dn(Bn({title:r("modelManager.noCustomLocationProvided"),status:"error"})));return}n(Dn(Bn({title:`${r("modelManager.convertingModelBegin")}: ${t.model_name}`,status:"success"}))),o(v).unwrap().then(b=>{n(Dn(Bn({title:`${r("modelManager.modelConverted")}: ${t.model_name}`,status:"success"})))}).catch(b=>{n(Dn(Bn({title:`${r("modelManager.modelConversionFailed")}: ${t.model_name}`,status:"error"})))})};return i.jsxs(Vy,{title:`${r("modelManager.convert")} ${t.model_name}`,acceptCallback:m,cancelCallback:h,acceptButtonText:`${r("modelManager.convert")}`,triggerComponent:i.jsxs(rn,{size:"sm","aria-label":r("modelManager.convertToDiffusers"),className:" modal-close-btn",isLoading:s,children:["🧨 ",r("modelManager.convertToDiffusers")]}),motionPreset:"slideInBottom",children:[i.jsxs(H,{flexDirection:"column",rowGap:4,children:[i.jsx(tt,{children:r("modelManager.convertToDiffusersHelpText1")}),i.jsxs(vb,{children:[i.jsx(xa,{children:r("modelManager.convertToDiffusersHelpText2")}),i.jsx(xa,{children:r("modelManager.convertToDiffusersHelpText3")}),i.jsx(xa,{children:r("modelManager.convertToDiffusersHelpText4")}),i.jsx(xa,{children:r("modelManager.convertToDiffusersHelpText5")})]}),i.jsx(tt,{children:r("modelManager.convertToDiffusersHelpText6")})]}),i.jsxs(H,{flexDir:"column",gap:2,children:[i.jsxs(H,{marginTop:4,flexDir:"column",gap:2,children:[i.jsx(tt,{fontWeight:"600",children:r("modelManager.convertToDiffusersSaveLocation")}),i.jsx(Gp,{value:a,onChange:v=>c(v),children:i.jsxs(H,{gap:4,children:[i.jsx(ba,{value:"InvokeAIRoot",children:i.jsx(wn,{label:"Save converted model in the InvokeAI root folder",children:r("modelManager.invokeRoot")})}),i.jsx(ba,{value:"Custom",children:i.jsx(wn,{label:"Save converted model in a custom folder",children:r("modelManager.custom")})})]})})]}),a==="Custom"&&i.jsxs(H,{flexDirection:"column",rowGap:2,children:[i.jsx(tt,{fontWeight:"500",fontSize:"sm",variant:"subtext",children:r("modelManager.customSaveLocation")}),i.jsx(Ec,{value:d,onChange:v=>{p(v.target.value)},width:"full"})]})]})]})}function pse(e){const t=z(jr),{model:n}=e,[r,{isLoading:o}]=J_(),{data:s}=K_(),[a,c]=f.useState(!1);f.useEffect(()=>{s!=null&&s.includes(n.config)||c(!0)},[s,n.config]);const d=te(),{t:p}=be(),h=qc({initialValues:{model_name:n.model_name?n.model_name:"",base_model:n.base_model,model_type:"main",path:n.path?n.path:"",description:n.description?n.description:"",model_format:"checkpoint",vae:n.vae?n.vae:"",config:n.config?n.config:"",variant:n.variant},validate:{path:v=>v.trim().length===0?"Must provide a path":null}}),m=f.useCallback(v=>{const b={base_model:n.base_model,model_name:n.model_name,body:v};r(b).unwrap().then(w=>{h.setValues(w),d(Dn(Bn({title:p("modelManager.modelUpdated"),status:"success"})))}).catch(w=>{h.reset(),d(Dn(Bn({title:p("modelManager.modelUpdateFailed"),status:"error"})))})},[h,d,n.base_model,n.model_name,p,r]);return i.jsxs(H,{flexDirection:"column",rowGap:4,width:"100%",children:[i.jsxs(H,{justifyContent:"space-between",alignItems:"center",children:[i.jsxs(H,{flexDirection:"column",children:[i.jsx(tt,{fontSize:"lg",fontWeight:"bold",children:n.model_name}),i.jsxs(tt,{fontSize:"sm",color:"base.400",children:[vr[n.base_model]," Model"]})]}),[""].includes(n.base_model)?i.jsx(pl,{sx:{p:2,borderRadius:4,bg:"error.200",_dark:{bg:"error.400"}},children:"Conversion Not Supported"}):i.jsx(fse,{model:n})]}),i.jsx(hl,{}),i.jsx(H,{flexDirection:"column",maxHeight:window.innerHeight-270,overflowY:"scroll",children:i.jsx("form",{onSubmit:h.onSubmit(v=>m(v)),children:i.jsxs(H,{flexDirection:"column",overflowY:"scroll",gap:4,children:[i.jsx(Tr,{label:p("modelManager.name"),...h.getInputProps("model_name")}),i.jsx(Tr,{label:p("modelManager.description"),...h.getInputProps("description")}),i.jsx(eg,{required:!0,...h.getInputProps("base_model")}),i.jsx(tg,{required:!0,...h.getInputProps("variant")}),i.jsx(Tr,{required:!0,label:p("modelManager.modelLocation"),...h.getInputProps("path")}),i.jsx(Tr,{label:p("modelManager.vaeLocation"),...h.getInputProps("vae")}),i.jsxs(H,{flexDirection:"column",gap:2,children:[a?i.jsx(Tr,{required:!0,label:p("modelManager.config"),...h.getInputProps("config")}):i.jsx(LO,{required:!0,...h.getInputProps("config")}),i.jsx(Gn,{isChecked:a,onChange:()=>c(!a),label:"Use Custom Config"})]}),i.jsx(rn,{type:"submit",isDisabled:t||o,isLoading:o,children:p("modelManager.updateModel")})]})})})]})}function hse(e){const t=z(jr),{model:n}=e,[r,{isLoading:o}]=J_(),s=te(),{t:a}=be(),c=qc({initialValues:{model_name:n.model_name?n.model_name:"",base_model:n.base_model,model_type:"main",path:n.path?n.path:"",description:n.description?n.description:"",model_format:"diffusers",vae:n.vae?n.vae:"",variant:n.variant},validate:{path:p=>p.trim().length===0?"Must provide a path":null}}),d=f.useCallback(p=>{const h={base_model:n.base_model,model_name:n.model_name,body:p};r(h).unwrap().then(m=>{c.setValues(m),s(Dn(Bn({title:a("modelManager.modelUpdated"),status:"success"})))}).catch(m=>{c.reset(),s(Dn(Bn({title:a("modelManager.modelUpdateFailed"),status:"error"})))})},[c,s,n.base_model,n.model_name,a,r]);return i.jsxs(H,{flexDirection:"column",rowGap:4,width:"100%",children:[i.jsxs(H,{flexDirection:"column",children:[i.jsx(tt,{fontSize:"lg",fontWeight:"bold",children:n.model_name}),i.jsxs(tt,{fontSize:"sm",color:"base.400",children:[vr[n.base_model]," Model"]})]}),i.jsx(hl,{}),i.jsx("form",{onSubmit:c.onSubmit(p=>d(p)),children:i.jsxs(H,{flexDirection:"column",overflowY:"scroll",gap:4,children:[i.jsx(Tr,{label:a("modelManager.name"),...c.getInputProps("model_name")}),i.jsx(Tr,{label:a("modelManager.description"),...c.getInputProps("description")}),i.jsx(eg,{required:!0,...c.getInputProps("base_model")}),i.jsx(tg,{required:!0,...c.getInputProps("variant")}),i.jsx(Tr,{required:!0,label:a("modelManager.modelLocation"),...c.getInputProps("path")}),i.jsx(Tr,{label:a("modelManager.vaeLocation"),...c.getInputProps("vae")}),i.jsx(rn,{type:"submit",isDisabled:t||o,isLoading:o,children:a("modelManager.updateModel")})]})})]})}const mse={"sd-1":"SD1","sd-2":"SD2",sdxl:"SDXL","sdxl-refiner":"SDXLR"};function qk(e){const t=z(jr),{t:n}=be(),r=te(),[o]=x7(),{model:s,isSelected:a,setSelectedModelId:c}=e,d=f.useCallback(()=>{c(s.id)},[s.id,c]),p=f.useCallback(()=>{o(s).unwrap().then(h=>{r(Dn(Bn({title:`${n("modelManager.modelDeleted")}: ${s.model_name}`,status:"success"})))}).catch(h=>{h&&r(Dn(Bn({title:`${n("modelManager.modelDeleteFailed")}: ${s.model_name}`,status:"success"})))}),c(void 0)},[o,s,c,r,n]);return i.jsxs(H,{sx:{gap:2,alignItems:"center",w:"full"},children:[i.jsx(H,{as:rn,isChecked:a,sx:{justifyContent:"start",p:2,borderRadius:"base",w:"full",alignItems:"center",bg:a?"accent.400":"base.100",color:a?"base.50":"base.800",_hover:{bg:a?"accent.500":"base.300",color:a?"base.50":"base.800"},_dark:{color:a?"base.50":"base.100",bg:a?"accent.600":"base.850",_hover:{color:a?"base.50":"base.100",bg:a?"accent.550":"base.700"}}},onClick:d,children:i.jsxs(H,{gap:4,alignItems:"center",children:[i.jsx(pl,{minWidth:14,p:.5,fontSize:"sm",variant:"solid",children:mse[s.base_model]}),i.jsx(wn,{label:s.description,hasArrow:!0,placement:"bottom",children:i.jsx(tt,{sx:{fontWeight:500},children:s.model_name})})]})}),i.jsx(Vy,{title:n("modelManager.deleteModel"),acceptCallback:p,acceptButtonText:n("modelManager.delete"),triggerComponent:i.jsx(Le,{icon:i.jsx(VV,{}),"aria-label":n("modelManager.deleteConfig"),isDisabled:t,colorScheme:"error"}),children:i.jsxs(H,{rowGap:4,flexDirection:"column",children:[i.jsx("p",{style:{fontWeight:"bold"},children:n("modelManager.deleteMsg1")}),i.jsx("p",{children:n("modelManager.deleteMsg2")})]})})]})}const gse=e=>{const{selectedModelId:t,setSelectedModelId:n}=e,{t:r}=be(),[o,s]=f.useState(""),[a,c]=f.useState("images"),{filteredDiffusersModels:d}=na(Hu,{selectFromResult:({data:m})=>({filteredDiffusersModels:Kk(m,"diffusers",o)})}),{filteredCheckpointModels:p}=na(Hu,{selectFromResult:({data:m})=>({filteredCheckpointModels:Kk(m,"checkpoint",o)})}),h=f.useCallback(m=>{s(m.target.value)},[]);return i.jsx(H,{flexDirection:"column",rowGap:4,width:"50%",minWidth:"50%",children:i.jsxs(H,{flexDirection:"column",gap:4,paddingInlineEnd:4,children:[i.jsxs(nr,{isAttached:!0,children:[i.jsx(rn,{onClick:()=>c("images"),isChecked:a==="images",size:"sm",children:r("modelManager.allModels")}),i.jsx(rn,{size:"sm",onClick:()=>c("diffusers"),isChecked:a==="diffusers",children:r("modelManager.diffusersModels")}),i.jsx(rn,{size:"sm",onClick:()=>c("checkpoint"),isChecked:a==="checkpoint",children:r("modelManager.checkpointModels")})]}),i.jsx(Ec,{onChange:h,label:r("modelManager.search"),labelPos:"side"}),i.jsxs(H,{flexDirection:"column",gap:4,maxHeight:window.innerHeight-280,overflow:"scroll",children:[["images","diffusers"].includes(a)&&d.length>0&&i.jsx(Yk,{children:i.jsxs(H,{sx:{gap:2,flexDir:"column"},children:[i.jsx(tt,{variant:"subtext",fontSize:"sm",children:"Diffusers"}),d.map(m=>i.jsx(qk,{model:m,isSelected:t===m.id,setSelectedModelId:n},m.id))]})}),["images","checkpoint"].includes(a)&&p.length>0&&i.jsx(Yk,{children:i.jsxs(H,{sx:{gap:2,flexDir:"column"},children:[i.jsx(tt,{variant:"subtext",fontSize:"sm",children:"Checkpoints"}),p.map(m=>i.jsx(qk,{model:m,isSelected:t===m.id,setSelectedModelId:n},m.id))]})})]})]})})},Kk=(e,t,n)=>{const r=[];return jo(e==null?void 0:e.entities,o=>{if(!o)return;const s=o.model_name.toLowerCase().includes(n.toLowerCase()),a=o.model_format===t;s&&a&&r.push(o)}),r},Yk=e=>i.jsx(H,{flexDirection:"column",gap:4,borderRadius:4,p:4,sx:{bg:"base.200",_dark:{bg:"base.800"}},children:e.children});function vse(){const[e,t]=f.useState(),{model:n}=na(Hu,{selectFromResult:({data:r})=>({model:e?r==null?void 0:r.entities[e]:void 0})});return i.jsxs(H,{sx:{gap:8,w:"full",h:"full"},children:[i.jsx(gse,{selectedModelId:e,setSelectedModelId:t}),i.jsx(bse,{model:n})]})}const bse=e=>{const{model:t}=e;return(t==null?void 0:t.model_format)==="checkpoint"?i.jsx(pse,{model:t},t.id):(t==null?void 0:t.model_format)==="diffusers"?i.jsx(hse,{model:t},t.id):i.jsx(H,{sx:{w:"full",h:"full",justifyContent:"center",alignItems:"center",maxH:96,userSelect:"none"},children:i.jsx(tt,{variant:"subtext",children:"No Model Selected"})})};function yse(){const{t:e}=be();return i.jsxs(H,{sx:{w:"full",p:4,borderRadius:4,gap:4,justifyContent:"space-between",alignItems:"center",bg:"base.200",_dark:{bg:"base.800"}},children:[i.jsxs(H,{sx:{flexDirection:"column",gap:2},children:[i.jsx(tt,{sx:{fontWeight:600},children:e("modelManager.syncModels")}),i.jsx(tt,{fontSize:"sm",sx:{_dark:{color:"base.400"}},children:e("modelManager.syncModelsDesc")})]}),i.jsx(Wd,{})]})}function xse(){return i.jsx(H,{children:i.jsx(yse,{})})}const Xk=[{id:"modelManager",label:Ln.t("modelManager.modelManager"),content:i.jsx(vse,{})},{id:"importModels",label:Ln.t("modelManager.importModels"),content:i.jsx(lse,{})},{id:"mergeModels",label:Ln.t("modelManager.mergeModels"),content:i.jsx(use,{})},{id:"settings",label:Ln.t("modelManager.settings"),content:i.jsx(xse,{})}],wse=()=>i.jsxs(Ed,{isLazy:!0,variant:"line",layerStyle:"first",sx:{w:"full",h:"full",p:4,gap:4,borderRadius:"base"},children:[i.jsx(Od,{children:Xk.map(e=>i.jsx(wc,{sx:{borderTopRadius:"base"},children:e.label},e.id))}),i.jsx(km,{sx:{w:"full",h:"full"},children:Xk.map(e=>i.jsx(Cm,{sx:{w:"full",h:"full"},children:e.content},e.id))})]}),Sse=f.memo(wse);const Cse=e=>fe([t=>t.nodes],t=>{const n=t.invocationTemplates[e];if(n)return n},{memoizeOptions:{resultEqualityCheck:(t,n)=>t!==void 0&&n!==void 0&&t.type===n.type}}),kse=(e,t)=>{const n={id:e,name:t.name,type:t.type};return t.inputRequirement!=="never"&&(t.type==="string"&&(n.value=t.default??""),t.type==="integer"&&(n.value=t.default??0),t.type==="float"&&(n.value=t.default??0),t.type==="boolean"&&(n.value=t.default??!1),t.type==="enum"&&(t.enumType==="number"&&(n.value=t.default??0),t.enumType==="string"&&(n.value=t.default??"")),t.type==="array"&&(n.value=t.default??1),t.type==="image"&&(n.value=void 0),t.type==="image_collection"&&(n.value=[]),t.type==="latents"&&(n.value=void 0),t.type==="conditioning"&&(n.value=void 0),t.type==="unet"&&(n.value=void 0),t.type==="clip"&&(n.value=void 0),t.type==="vae"&&(n.value=void 0),t.type==="control"&&(n.value=void 0),t.type==="model"&&(n.value=void 0),t.type==="refiner_model"&&(n.value=void 0),t.type==="vae_model"&&(n.value=void 0),t.type==="lora_model"&&(n.value=void 0),t.type==="controlnet_model"&&(n.value=void 0)),n},_se=fe([e=>e.nodes],e=>e.invocationTemplates),Uy="node-drag-handle",Qk={dragHandle:`.${Uy}`},Pse=()=>{const e=z(_se),t=G1();return f.useCallback(n=>{if(n==="progress_image"){const{x:h,y:m}=t.project({x:window.innerWidth/2.5,y:window.innerHeight/8});return{...Qk,id:"progress_image",type:"progress_image",position:{x:h,y:m},data:{}}}const r=e[n];if(r===void 0){console.error(`Unable to find template ${n}.`);return}const o=ui(),s=rw(r.inputs,(h,m,v)=>{const b=ui(),w=kse(b,m);return h[v]=w,h},{}),a=rw(r.outputs,(h,m,v)=>{const w={id:ui(),name:v,type:m.type};return h[v]=w,h},{}),{x:c,y:d}=t.project({x:window.innerWidth/2.5,y:window.innerHeight/8});return{...Qk,id:o,type:"invocation",position:{x:c,y:d},data:{id:o,type:n,inputs:s,outputs:a}}},[e,t])},jse=e=>{const{nodeId:t,title:n,description:r}=e;return i.jsxs(H,{className:Uy,sx:{borderTopRadius:"md",alignItems:"center",justifyContent:"space-between",px:2,py:1,bg:"base.100",_dark:{bg:"base.900"}},children:[i.jsx(wn,{label:t,children:i.jsx(Xs,{size:"xs",sx:{fontWeight:600,color:"base.900",_dark:{color:"base.200"}},children:n})}),i.jsx(wn,{label:r,placement:"top",hasArrow:!0,shouldWrapChildren:!0,children:i.jsx(Kr,{sx:{h:"min-content",color:"base.700",_dark:{color:"base.300"}},as:nW})})]})},WO=f.memo(jse),VO=()=>()=>!0,Ise={position:"absolute",width:"1rem",height:"1rem",borderWidth:0},Ese={left:"-1rem"},Ose={right:"-0.5rem"},Rse=e=>{const{field:t,isValidConnection:n,handleType:r,styles:o}=e,{name:s,type:a}=t;return i.jsx(wn,{label:a,placement:r==="target"?"start":"end",hasArrow:!0,openDelay:Z_,children:i.jsx(w7,{type:r,id:s,isValidConnection:n,position:r==="target"?ow.Left:ow.Right,style:{backgroundColor:e3[a].colorCssVar,...o,...Ise,...r==="target"?Ese:Ose}})})},UO=f.memo(Rse),Mse=e=>i.jsx(sW,{}),Dse=f.memo(Mse),Tse=e=>{const{nodeId:t,field:n}=e,r=te(),o=s=>{r(Ts({nodeId:t,fieldName:n.name,value:s.target.checked}))};return i.jsx(Nb,{onChange:o,isChecked:n.value})},Ase=f.memo(Tse),Nse=e=>null,$se=f.memo(Nse);function ng(){return(ng=Object.assign||function(e){for(var t=1;t=0||(o[n]=e[n]);return o}function _1(e){var t=f.useRef(e),n=f.useRef(function(r){t.current&&t.current(r)});return t.current=e,n.current}var Oc=function(e,t,n){return t===void 0&&(t=0),n===void 0&&(n=1),e>n?n:e0:S.buttons>0)&&o.current?s(Jk(o.current,S,c.current)):y(!1)},w=function(){return y(!1)};function y(S){var k=d.current,_=P1(o.current),I=S?_.addEventListener:_.removeEventListener;I(k?"touchmove":"mousemove",b),I(k?"touchend":"mouseup",w)}return[function(S){var k=S.nativeEvent,_=o.current;if(_&&(Zk(k),!function(P,E){return E&&!Fu(P)}(k,d.current)&&_)){if(Fu(k)){d.current=!0;var I=k.changedTouches||[];I.length&&(c.current=I[0].identifier)}_.focus(),s(Jk(_,k,c.current)),y(!0)}},function(S){var k=S.which||S.keyCode;k<37||k>40||(S.preventDefault(),a({left:k===39?.05:k===37?-.05:0,top:k===40?.05:k===38?-.05:0}))},y]},[a,s]),h=p[0],m=p[1],v=p[2];return f.useEffect(function(){return v},[v]),F.createElement("div",ng({},r,{onTouchStart:h,onMouseDown:h,className:"react-colorful__interactive",ref:o,onKeyDown:m,tabIndex:0,role:"slider"}))}),rg=function(e){return e.filter(Boolean).join(" ")},qy=function(e){var t=e.color,n=e.left,r=e.top,o=r===void 0?.5:r,s=rg(["react-colorful__pointer",e.className]);return F.createElement("div",{className:s,style:{top:100*o+"%",left:100*n+"%"}},F.createElement("div",{className:"react-colorful__pointer-fill",style:{backgroundColor:t}}))},fo=function(e,t,n){return t===void 0&&(t=0),n===void 0&&(n=Math.pow(10,t)),Math.round(n*e)/n},qO=function(e){var t=e.s,n=e.v,r=e.a,o=(200-t)*n/100;return{h:fo(e.h),s:fo(o>0&&o<200?t*n/100/(o<=100?o:200-o)*100:0),l:fo(o/2),a:fo(r,2)}},j1=function(e){var t=qO(e);return"hsl("+t.h+", "+t.s+"%, "+t.l+"%)"},ov=function(e){var t=qO(e);return"hsla("+t.h+", "+t.s+"%, "+t.l+"%, "+t.a+")"},zse=function(e){var t=e.h,n=e.s,r=e.v,o=e.a;t=t/360*6,n/=100,r/=100;var s=Math.floor(t),a=r*(1-n),c=r*(1-(t-s)*n),d=r*(1-(1-t+s)*n),p=s%6;return{r:fo(255*[r,c,a,a,d,r][p]),g:fo(255*[d,r,r,c,a,a][p]),b:fo(255*[a,a,d,r,r,c][p]),a:fo(o,2)}},Lse=function(e){var t=e.r,n=e.g,r=e.b,o=e.a,s=Math.max(t,n,r),a=s-Math.min(t,n,r),c=a?s===t?(n-r)/a:s===n?2+(r-t)/a:4+(t-n)/a:0;return{h:fo(60*(c<0?c+6:c)),s:fo(s?a/s*100:0),v:fo(s/255*100),a:o}},Bse=F.memo(function(e){var t=e.hue,n=e.onChange,r=rg(["react-colorful__hue",e.className]);return F.createElement("div",{className:r},F.createElement(Gy,{onMove:function(o){n({h:360*o.left})},onKey:function(o){n({h:Oc(t+360*o.left,0,360)})},"aria-label":"Hue","aria-valuenow":fo(t),"aria-valuemax":"360","aria-valuemin":"0"},F.createElement(qy,{className:"react-colorful__hue-pointer",left:t/360,color:j1({h:t,s:100,v:100,a:1})})))}),Fse=F.memo(function(e){var t=e.hsva,n=e.onChange,r={backgroundColor:j1({h:t.h,s:100,v:100,a:1})};return F.createElement("div",{className:"react-colorful__saturation",style:r},F.createElement(Gy,{onMove:function(o){n({s:100*o.left,v:100-100*o.top})},onKey:function(o){n({s:Oc(t.s+100*o.left,0,100),v:Oc(t.v-100*o.top,0,100)})},"aria-label":"Color","aria-valuetext":"Saturation "+fo(t.s)+"%, Brightness "+fo(t.v)+"%"},F.createElement(qy,{className:"react-colorful__saturation-pointer",top:1-t.v/100,left:t.s/100,color:j1(t)})))}),KO=function(e,t){if(e===t)return!0;for(var n in e)if(e[n]!==t[n])return!1;return!0};function Hse(e,t,n){var r=_1(n),o=f.useState(function(){return e.toHsva(t)}),s=o[0],a=o[1],c=f.useRef({color:t,hsva:s});f.useEffect(function(){if(!e.equal(t,c.current.color)){var p=e.toHsva(t);c.current={hsva:p,color:t},a(p)}},[t,e]),f.useEffect(function(){var p;KO(s,c.current.hsva)||e.equal(p=e.fromHsva(s),c.current.color)||(c.current={hsva:s,color:p},r(p))},[s,e,r]);var d=f.useCallback(function(p){a(function(h){return Object.assign({},h,p)})},[]);return[s,d]}var Wse=typeof window<"u"?f.useLayoutEffect:f.useEffect,Vse=function(){return typeof __webpack_nonce__<"u"?__webpack_nonce__:void 0},e_=new Map,Use=function(e){Wse(function(){var t=e.current?e.current.ownerDocument:document;if(t!==void 0&&!e_.has(t)){var n=t.createElement("style");n.innerHTML=`.react-colorful{position:relative;display:flex;flex-direction:column;width:200px;height:200px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:default}.react-colorful__saturation{position:relative;flex-grow:1;border-color:transparent;border-bottom:12px solid #000;border-radius:8px 8px 0 0;background-image:linear-gradient(0deg,#000,transparent),linear-gradient(90deg,#fff,hsla(0,0%,100%,0))}.react-colorful__alpha-gradient,.react-colorful__pointer-fill{content:"";position:absolute;left:0;top:0;right:0;bottom:0;pointer-events:none;border-radius:inherit}.react-colorful__alpha-gradient,.react-colorful__saturation{box-shadow:inset 0 0 0 1px rgba(0,0,0,.05)}.react-colorful__alpha,.react-colorful__hue{position:relative;height:24px}.react-colorful__hue{background:linear-gradient(90deg,red 0,#ff0 17%,#0f0 33%,#0ff 50%,#00f 67%,#f0f 83%,red)}.react-colorful__last-control{border-radius:0 0 8px 8px}.react-colorful__interactive{position:absolute;left:0;top:0;right:0;bottom:0;border-radius:inherit;outline:none;touch-action:none}.react-colorful__pointer{position:absolute;z-index:1;box-sizing:border-box;width:28px;height:28px;transform:translate(-50%,-50%);background-color:#fff;border:2px solid #fff;border-radius:50%;box-shadow:0 2px 4px rgba(0,0,0,.2)}.react-colorful__interactive:focus .react-colorful__pointer{transform:translate(-50%,-50%) scale(1.1)}.react-colorful__alpha,.react-colorful__alpha-pointer{background-color:#fff;background-image:url('data:image/svg+xml;charset=utf-8,')}.react-colorful__saturation-pointer{z-index:3}.react-colorful__hue-pointer{z-index:2}`,e_.set(t,n);var r=Vse();r&&n.setAttribute("nonce",r),t.head.appendChild(n)}},[])},Gse=function(e){var t=e.className,n=e.hsva,r=e.onChange,o={backgroundImage:"linear-gradient(90deg, "+ov(Object.assign({},n,{a:0}))+", "+ov(Object.assign({},n,{a:1}))+")"},s=rg(["react-colorful__alpha",t]),a=fo(100*n.a);return F.createElement("div",{className:s},F.createElement("div",{className:"react-colorful__alpha-gradient",style:o}),F.createElement(Gy,{onMove:function(c){r({a:c.left})},onKey:function(c){r({a:Oc(n.a+c.left)})},"aria-label":"Alpha","aria-valuetext":a+"%","aria-valuenow":a,"aria-valuemin":"0","aria-valuemax":"100"},F.createElement(qy,{className:"react-colorful__alpha-pointer",left:n.a,color:ov(n)})))},qse=function(e){var t=e.className,n=e.colorModel,r=e.color,o=r===void 0?n.defaultColor:r,s=e.onChange,a=GO(e,["className","colorModel","color","onChange"]),c=f.useRef(null);Use(c);var d=Hse(n,o,s),p=d[0],h=d[1],m=rg(["react-colorful",t]);return F.createElement("div",ng({},a,{ref:c,className:m}),F.createElement(Fse,{hsva:p,onChange:h}),F.createElement(Bse,{hue:p.h,onChange:h}),F.createElement(Gse,{hsva:p,onChange:h,className:"react-colorful__last-control"}))},Kse={defaultColor:{r:0,g:0,b:0,a:1},toHsva:Lse,fromHsva:zse,equal:KO},YO=function(e){return F.createElement(qse,ng({},e,{colorModel:Kse}))};const Yse=e=>{const{nodeId:t,field:n}=e,r=te(),o=s=>{r(Ts({nodeId:t,fieldName:n.name,value:s}))};return i.jsx(YO,{className:"nodrag",color:n.value,onChange:o})},Xse=f.memo(Yse),Qse=e=>null,Jse=f.memo(Qse),Zse=e=>null,eae=f.memo(Zse),tae=e=>{const{nodeId:t,field:n}=e,r=n.value,o=te(),{data:s}=U1(),a=f.useMemo(()=>(s==null?void 0:s.entities[`${r==null?void 0:r.base_model}/controlnet/${r==null?void 0:r.model_name}`])??null,[r==null?void 0:r.base_model,r==null?void 0:r.model_name,s==null?void 0:s.entities]),c=f.useMemo(()=>{if(!s)return[];const p=[];return jo(s.entities,(h,m)=>{h&&p.push({value:m,label:h.model_name,group:vr[h.base_model]})}),p},[s]),d=f.useCallback(p=>{if(!p)return;const h=DO(p);h&&o(Ts({nodeId:t,fieldName:n.name,value:h}))},[o,n.name,t]);return i.jsx(Yr,{tooltip:a==null?void 0:a.description,label:(a==null?void 0:a.base_model)&&vr[a==null?void 0:a.base_model],value:(a==null?void 0:a.id)??null,placeholder:"Pick one",error:!a,data:c,onChange:d})},nae=f.memo(tae),rae=e=>{const{nodeId:t,field:n,template:r}=e,o=te(),s=a=>{o(Ts({nodeId:t,fieldName:n.name,value:a.target.value}))};return i.jsx(_5,{onChange:s,value:n.value,children:r.options.map(a=>i.jsx("option",{children:a},a))})},oae=f.memo(rae),sae=e=>{var c;const{nodeId:t,field:n}=e,r={id:`node-${t}-${n.name}`,actionType:"SET_MULTI_NODES_IMAGE",context:{nodeId:t,fieldName:n.name}},{isOver:o,setNodeRef:s,active:a}=A1({id:`node_${t}`,data:r});return i.jsxs(H,{ref:s,sx:{w:"full",h:"full",alignItems:"center",justifyContent:"center",position:"relative",minH:"10rem"},children:[(c=n.value)==null?void 0:c.map(({image_name:d})=>i.jsx(iae,{imageName:d},d)),Ep(r,a)&&i.jsx(nh,{isOver:o})]})},aae=f.memo(sae),iae=e=>{const{currentData:t}=os(e.imageName);return i.jsx(yi,{imageDTO:t,isDropDisabled:!0,isDragDisabled:!0})},lae=e=>{var p;const{nodeId:t,field:n}=e,r=te(),{currentData:o}=os(((p=n.value)==null?void 0:p.image_name)??oo.skipToken),s=f.useCallback(()=>{r(Ts({nodeId:t,fieldName:n.name,value:void 0}))},[r,n.name,t]),a=f.useMemo(()=>{if(o)return{id:`node-${t}-${n.name}`,payloadType:"IMAGE_DTO",payload:{imageDTO:o}}},[n.name,o,t]),c=f.useMemo(()=>({id:`node-${t}-${n.name}`,actionType:"SET_NODES_IMAGE",context:{nodeId:t,fieldName:n.name}}),[n.name,t]),d=f.useMemo(()=>({type:"SET_NODES_IMAGE",nodeId:t,fieldName:n.name}),[t,n.name]);return i.jsx(H,{sx:{w:"full",h:"full",alignItems:"center",justifyContent:"center"},children:i.jsx(yi,{imageDTO:o,droppableData:c,draggableData:a,onClickReset:s,postUploadAction:d})})},cae=f.memo(lae),uae=e=>i.jsx(AH,{}),t_=f.memo(uae),dae=e=>null,fae=f.memo(dae),pae=e=>{const t=tm("models"),[n,r,o]=e.split("/"),s=S7.safeParse({base_model:n,model_name:o});if(!s.success){t.error({loraModelId:e,errors:s.error.format()},"Failed to parse LoRA model id");return}return s.data},hae=e=>{const{nodeId:t,field:n}=e,r=n.value,o=te(),{data:s}=U_(),a=f.useMemo(()=>{if(!s)return[];const p=[];return jo(s.entities,(h,m)=>{h&&p.push({value:m,label:h.model_name,group:vr[h.base_model]})}),p.sort((h,m)=>h.disabled&&!m.disabled?1:-1)},[s]),c=f.useMemo(()=>(s==null?void 0:s.entities[`${r==null?void 0:r.base_model}/lora/${r==null?void 0:r.model_name}`])??null,[s==null?void 0:s.entities,r==null?void 0:r.base_model,r==null?void 0:r.model_name]),d=f.useCallback(p=>{if(!p)return;const h=pae(p);h&&o(Ts({nodeId:t,fieldName:n.name,value:h}))},[o,n.name,t]);return(s==null?void 0:s.ids.length)===0?i.jsx(H,{sx:{justifyContent:"center",p:2},children:i.jsx(tt,{sx:{fontSize:"sm",color:"base.500",_dark:"base.700"},children:"No LoRAs Loaded"})}):i.jsx(sr,{value:(c==null?void 0:c.id)??null,label:(c==null?void 0:c.base_model)&&vr[c==null?void 0:c.base_model],placeholder:a.length>0?"Select a LoRA":"No LoRAs available",data:a,nothingFound:"No matching LoRAs",itemComponent:Oi,disabled:a.length===0,filter:(p,h)=>{var m;return((m=h.label)==null?void 0:m.toLowerCase().includes(p.toLowerCase().trim()))||h.value.toLowerCase().includes(p.toLowerCase().trim())},onChange:d})},mae=f.memo(hae),gae=e=>{var m,v;const{nodeId:t,field:n}=e,r=te(),{t:o}=be(),s=ar("syncModels").isFeatureEnabled,{data:a,isLoading:c}=na(W1),d=f.useMemo(()=>{if(!a)return[];const b=[];return jo(a.entities,(w,y)=>{w&&b.push({value:y,label:w.model_name,group:vr[w.base_model]})}),b},[a]),p=f.useMemo(()=>{var b,w;return(a==null?void 0:a.entities[`${(b=n.value)==null?void 0:b.base_model}/main/${(w=n.value)==null?void 0:w.model_name}`])??null},[(m=n.value)==null?void 0:m.base_model,(v=n.value)==null?void 0:v.model_name,a==null?void 0:a.entities]),h=f.useCallback(b=>{if(!b)return;const w=Jm(b);w&&r(Ts({nodeId:t,fieldName:n.name,value:w}))},[r,n.name,t]);return c?i.jsx(sr,{label:o("modelManager.model"),placeholder:"Loading...",disabled:!0,data:[]}):i.jsxs(H,{w:"100%",alignItems:"center",gap:2,children:[i.jsx(sr,{tooltip:p==null?void 0:p.description,label:(p==null?void 0:p.base_model)&&vr[p==null?void 0:p.base_model],value:p==null?void 0:p.id,placeholder:d.length>0?"Select a model":"No models available",data:d,error:d.length===0,disabled:d.length===0,onChange:h}),s&&i.jsx(Oe,{mt:7,children:i.jsx(Wd,{iconMode:!0})})]})},vae=f.memo(gae),bae=e=>{const{nodeId:t,field:n}=e,r=te(),[o,s]=f.useState(String(n.value)),a=c=>{s(c),c.match(Kh)||r(Ts({nodeId:t,fieldName:n.name,value:e.template.type==="integer"?Math.floor(Number(c)):Number(c)}))};return f.useEffect(()=>{!o.match(Kh)&&n.value!==Number(o)&&s(String(n.value))},[n.value,o]),i.jsxs(dm,{onChange:a,value:o,step:e.template.type==="integer"?1:.1,precision:e.template.type==="integer"?0:3,children:[i.jsx(pm,{}),i.jsxs(fm,{children:[i.jsx(mm,{}),i.jsx(hm,{})]})]})},yae=f.memo(bae),xae=e=>{const{nodeId:t,field:n}=e,r=te(),o=s=>{r(Ts({nodeId:t,fieldName:n.name,value:s.target.value}))};return i.jsx(yd,{onChange:o,value:n.value})},wae=f.memo(xae),Sae=e=>null,Cae=f.memo(Sae),kae=e=>null,_ae=f.memo(kae),Pae=e=>{const{nodeId:t,field:n}=e,r=n.value,o=te(),{data:s}=F_(),a=f.useMemo(()=>{if(!s)return[];const p=[{value:"default",label:"Default",group:"Default"}];return jo(s.entities,(h,m)=>{h&&p.push({value:m,label:h.model_name,group:vr[h.base_model]})}),p.sort((h,m)=>h.disabled&&!m.disabled?1:-1)},[s]),c=f.useMemo(()=>(s==null?void 0:s.entities[`${r==null?void 0:r.base_model}/vae/${r==null?void 0:r.model_name}`])??null,[s==null?void 0:s.entities,r]),d=f.useCallback(p=>{if(!p)return;const h=_O(p);h&&o(Ts({nodeId:t,fieldName:n.name,value:h}))},[o,n.name,t]);return i.jsx(sr,{itemComponent:Oi,tooltip:c==null?void 0:c.description,label:(c==null?void 0:c.base_model)&&vr[c==null?void 0:c.base_model],value:(c==null?void 0:c.id)??"default",placeholder:"Default",data:a,onChange:d,disabled:a.length===0,clearable:!0})},jae=f.memo(Pae),Iae=e=>{var m,v;const{nodeId:t,field:n}=e,r=te(),{t:o}=be(),s=ar("syncModels").isFeatureEnabled,{data:a,isLoading:c}=na(V1),d=f.useMemo(()=>{if(!a)return[];const b=[];return jo(a.entities,(w,y)=>{w&&b.push({value:y,label:w.model_name,group:vr[w.base_model]})}),b},[a]),p=f.useMemo(()=>{var b,w;return(a==null?void 0:a.entities[`${(b=n.value)==null?void 0:b.base_model}/main/${(w=n.value)==null?void 0:w.model_name}`])??null},[(m=n.value)==null?void 0:m.base_model,(v=n.value)==null?void 0:v.model_name,a==null?void 0:a.entities]),h=f.useCallback(b=>{if(!b)return;const w=Jm(b);w&&r(Ts({nodeId:t,fieldName:n.name,value:w}))},[r,n.name,t]);return c?i.jsx(sr,{label:o("modelManager.model"),placeholder:"Loading...",disabled:!0,data:[]}):i.jsxs(H,{w:"100%",alignItems:"center",gap:2,children:[i.jsx(sr,{tooltip:p==null?void 0:p.description,label:(p==null?void 0:p.base_model)&&vr[p==null?void 0:p.base_model],value:p==null?void 0:p.id,placeholder:d.length>0?"Select a model":"No models available",data:d,error:d.length===0,disabled:d.length===0,onChange:h}),s&&i.jsx(Oe,{mt:7,children:i.jsx(Wd,{iconMode:!0})})]})},Eae=f.memo(Iae),Oae=e=>{const{nodeId:t,field:n,template:r}=e,{type:o}=n;return o==="string"&&r.type==="string"?i.jsx(wae,{nodeId:t,field:n,template:r}):o==="boolean"&&r.type==="boolean"?i.jsx(Ase,{nodeId:t,field:n,template:r}):o==="integer"&&r.type==="integer"||o==="float"&&r.type==="float"?i.jsx(yae,{nodeId:t,field:n,template:r}):o==="enum"&&r.type==="enum"?i.jsx(oae,{nodeId:t,field:n,template:r}):o==="image"&&r.type==="image"?i.jsx(cae,{nodeId:t,field:n,template:r}):o==="latents"&&r.type==="latents"?i.jsx(fae,{nodeId:t,field:n,template:r}):o==="conditioning"&&r.type==="conditioning"?i.jsx(Jse,{nodeId:t,field:n,template:r}):o==="unet"&&r.type==="unet"?i.jsx(Cae,{nodeId:t,field:n,template:r}):o==="clip"&&r.type==="clip"?i.jsx($se,{nodeId:t,field:n,template:r}):o==="vae"&&r.type==="vae"?i.jsx(_ae,{nodeId:t,field:n,template:r}):o==="control"&&r.type==="control"?i.jsx(eae,{nodeId:t,field:n,template:r}):o==="model"&&r.type==="model"?i.jsx(vae,{nodeId:t,field:n,template:r}):o==="refiner_model"&&r.type==="refiner_model"?i.jsx(Eae,{nodeId:t,field:n,template:r}):o==="vae_model"&&r.type==="vae_model"?i.jsx(jae,{nodeId:t,field:n,template:r}):o==="lora_model"&&r.type==="lora_model"?i.jsx(mae,{nodeId:t,field:n,template:r}):o==="controlnet_model"&&r.type==="controlnet_model"?i.jsx(nae,{nodeId:t,field:n,template:r}):o==="array"&&r.type==="array"?i.jsx(Dse,{nodeId:t,field:n,template:r}):o==="item"&&r.type==="item"?i.jsx(t_,{nodeId:t,field:n,template:r}):o==="color"&&r.type==="color"?i.jsx(Xse,{nodeId:t,field:n,template:r}):o==="item"&&r.type==="item"?i.jsx(t_,{nodeId:t,field:n,template:r}):o==="image_collection"&&r.type==="image_collection"?i.jsx(aae,{nodeId:t,field:n,template:r}):i.jsxs(Oe,{p:2,children:["Unknown field type: ",o]})},Rae=f.memo(Oae);function Mae(e){const{nodeId:t,input:n,template:r,connected:o}=e,s=VO();return i.jsx(Oe,{className:"nopan",position:"relative",borderColor:r?!o&&["always","connectionOnly"].includes(String(r==null?void 0:r.inputRequirement))&&n.value===void 0?"warning.400":void 0:"error.400",children:i.jsx(ho,{isDisabled:r?o:!0,pl:2,children:r?i.jsxs(i.Fragment,{children:[i.jsxs(di,{justifyContent:"space-between",alignItems:"center",children:[i.jsx(di,{children:i.jsx(wn,{label:r==null?void 0:r.description,placement:"top",hasArrow:!0,shouldWrapChildren:!0,openDelay:Z_,children:i.jsx(zo,{children:r==null?void 0:r.title})})}),i.jsx(Rae,{nodeId:t,field:n,template:r})]}),!["never","directOnly"].includes((r==null?void 0:r.inputRequirement)??"")&&i.jsx(UO,{nodeId:t,field:r,isValidConnection:s,handleType:"target"})]}):i.jsx(di,{justifyContent:"space-between",alignItems:"center",children:i.jsxs(zo,{children:["Unknown input: ",n.name]})})})})}const Dae=e=>{const{nodeId:t,template:n,inputs:r}=e,o=z(a=>a.nodes.edges);return f.useCallback(()=>{const a=[],c=cs(r);return c.forEach((d,p)=>{const h=n.inputs[d.name],m=!!o.filter(v=>v.target===t&&v.targetHandle===d.name).length;p{const{nodeId:t,template:n,outputs:r}=e,o=z(a=>a.nodes.edges);return f.useCallback(()=>{const a=[];return cs(r).forEach(d=>{const p=n.outputs[d.name],h=!!o.filter(m=>m.source===t&&m.sourceHandle===d.name).length;a.push(i.jsx(Aae,{nodeId:t,output:d,template:p,connected:h},d.id))}),i.jsx(H,{flexDir:"column",children:a})},[o,t,r,n.outputs])()},$ae=f.memo(Nae),zae=e=>{const{...t}=e;return i.jsx(MT,{style:{position:"absolute",border:"none",background:"transparent",width:15,height:15,bottom:0,right:0},minWidth:t3,...t})},I1=f.memo(zae),E1=e=>{const[t,n]=Dc("shadows",["nodeSelectedOutline","dark-lg"]),r=z(o=>o.hotkeys.shift);return i.jsx(Oe,{className:r?Uy:"nopan",sx:{position:"relative",borderRadius:"md",minWidth:t3,shadow:e.selected?`${t}, ${n}`:`${n}`},children:e.children})},XO=f.memo(e=>{const{id:t,data:n,selected:r}=e,{type:o,inputs:s,outputs:a}=n,c=f.useMemo(()=>Cse(o),[o]),d=z(c);return d?i.jsxs(E1,{selected:r,children:[i.jsx(WO,{nodeId:t,title:d.title,description:d.description}),i.jsxs(H,{className:"nopan",sx:{cursor:"auto",flexDirection:"column",borderBottomRadius:"md",py:2,bg:"base.150",_dark:{bg:"base.800"}},children:[i.jsx($ae,{nodeId:t,outputs:a,template:d}),i.jsx(Tae,{nodeId:t,inputs:s,template:d})]}),i.jsx(I1,{})]}):i.jsx(E1,{selected:r,children:i.jsxs(H,{className:"nopan",sx:{alignItems:"center",justifyContent:"center",cursor:"auto"},children:[i.jsx(Kr,{as:h6,sx:{boxSize:32,color:"base.600",_dark:{color:"base.400"}}}),i.jsx(I1,{})]})})});XO.displayName="InvocationComponent";const Lae=e=>{const t=sw(a=>a.system.progressImage),n=sw(a=>a.nodes.progressNodeSize),r=C7(),{selected:o}=e,s=(a,c)=>{r(k7(c))};return i.jsxs(E1,{selected:o,children:[i.jsx(WO,{title:"Progress Image",description:"Displays the progress image in the Node Editor"}),i.jsx(H,{sx:{flexDirection:"column",flexShrink:0,borderBottomRadius:"md",bg:"base.200",_dark:{bg:"base.800"},width:n.width-2,height:n.height-2,minW:250,minH:250,overflow:"hidden"},children:t?i.jsx(Tc,{src:t.dataURL,sx:{w:"full",h:"full",objectFit:"contain"}}):i.jsx(H,{sx:{minW:250,minH:250,width:n.width-2,height:n.height-2},children:i.jsx(mi,{})})}),i.jsx(I1,{onResize:s})]})},Bae=f.memo(Lae),Fae=()=>{const{t:e}=be(),{zoomIn:t,zoomOut:n,fitView:r}=G1(),o=te(),s=z(w=>w.nodes.shouldShowGraphOverlay),a=z(w=>w.nodes.shouldShowFieldTypeLegend),c=z(w=>w.nodes.shouldShowMinimapPanel),d=f.useCallback(()=>{t()},[t]),p=f.useCallback(()=>{n()},[n]),h=f.useCallback(()=>{r()},[r]),m=f.useCallback(()=>{o(_7(!s))},[s,o]),v=f.useCallback(()=>{o(P7(!a))},[a,o]),b=f.useCallback(()=>{o(j7(!c))},[c,o]);return i.jsxs(nr,{isAttached:!0,orientation:"vertical",children:[i.jsx(wn,{label:e("nodes.zoomInNodes"),children:i.jsx(Le,{"aria-label":"Zoom in ",onClick:d,icon:i.jsx(ml,{})})}),i.jsx(wn,{label:e("nodes.zoomOutNodes"),children:i.jsx(Le,{"aria-label":"Zoom out",onClick:p,icon:i.jsx(lW,{})})}),i.jsx(wn,{label:e("nodes.fitViewportNodes"),children:i.jsx(Le,{"aria-label":"Fit viewport",onClick:h,icon:i.jsx(YH,{})})}),i.jsx(wn,{label:e(s?"nodes.hideGraphNodes":"nodes.showGraphNodes"),children:i.jsx(Le,{"aria-label":"Toggle nodes graph overlay",isChecked:s,onClick:m,icon:i.jsx(Lb,{})})}),i.jsx(wn,{label:e(a?"nodes.hideLegendNodes":"nodes.showLegendNodes"),children:i.jsx(Le,{"aria-label":"Toggle field type legend",isChecked:a,onClick:v,icon:i.jsx(rW,{})})}),i.jsx(wn,{label:e(c?"nodes.hideMinimapnodes":"nodes.showMinimapnodes"),children:i.jsx(Le,{"aria-label":"Toggle minimap",isChecked:c,onClick:b,icon:i.jsx(aW,{})})})]})},Hae=f.memo(Fae),Wae=()=>i.jsx(id,{position:"bottom-left",children:i.jsx(Hae,{})}),Vae=f.memo(Wae),Uae=()=>{const e=vp({background:"var(--invokeai-colors-base-200)"},{background:"var(--invokeai-colors-base-500)"}),t=z(o=>o.nodes.shouldShowMinimapPanel),n=vp("var(--invokeai-colors-accent-300)","var(--invokeai-colors-accent-700)"),r=vp("var(--invokeai-colors-blackAlpha-300)","var(--invokeai-colors-blackAlpha-600)");return i.jsx(i.Fragment,{children:t&&i.jsx(ST,{nodeStrokeWidth:3,pannable:!0,zoomable:!0,nodeBorderRadius:30,style:e,nodeColor:n,maskColor:r})})},Gae=f.memo(Uae),qae=()=>{const{t:e}=be(),t=te(),{isOpen:n,onOpen:r,onClose:o}=ss(),s=f.useRef(null),a=z(d=>d.nodes.nodes),c=f.useCallback(()=>{t(I7()),t(Dn(Bn({title:e("toast.nodesCleared"),status:"success"}))),o()},[t,e,o]);return i.jsxs(i.Fragment,{children:[i.jsx(Le,{icon:i.jsx(us,{}),tooltip:e("nodes.clearGraph"),"aria-label":e("nodes.clearGraph"),onClick:r,isDisabled:a.length===0}),i.jsxs(Pd,{isOpen:n,onClose:o,leastDestructiveRef:s,isCentered:!0,children:[i.jsx(Ma,{}),i.jsxs(jd,{children:[i.jsx(Ra,{fontSize:"lg",fontWeight:"bold",children:e("nodes.clearGraph")}),i.jsx(Da,{children:i.jsx(tt,{children:e("nodes.clearGraphDesc")})}),i.jsxs(Oa,{children:[i.jsx(gc,{ref:s,onClick:o,children:e("common.cancel")}),i.jsx(gc,{colorScheme:"red",ml:3,onClick:c,children:e("common.accept")})]})]})]})]})},Kae=f.memo(qae);function Yae(e){const t=["nodes","edges","viewport"];for(const s of t)if(!(s in e))return{isValid:!1,message:Ln.t("toast.nodesNotValidGraph")};if(!Array.isArray(e.nodes)||!Array.isArray(e.edges))return{isValid:!1,message:Ln.t("toast.nodesNotValidGraph")};const n=["data","type"],r=["invocation","progress_image"];if(e.nodes.length>0)for(const s of e.nodes)for(const a of n){if(!(a in s))return{isValid:!1,message:Ln.t("toast.nodesNotValidGraph")};if(a==="type"&&!r.includes(s[a]))return{isValid:!1,message:Ln.t("toast.nodesUnrecognizedTypes")}}const o=["source","sourceHandle","target","targetHandle"];if(e.edges.length>0){for(const s of e.edges)for(const a of o)if(!(a in s))return{isValid:!1,message:Ln.t("toast.nodesBrokenConnections")}}return{isValid:!0,message:Ln.t("toast.nodesLoaded")}}const Xae=()=>{const{t:e}=be(),t=te(),{fitView:n}=G1(),r=f.useRef(null),o=f.useCallback(s=>{var c;if(!s)return;const a=new FileReader;a.onload=async()=>{const d=a.result;try{const p=await JSON.parse(String(d)),{isValid:h,message:m}=Yae(p);h?(t(E7(p.nodes)),t(O7(p.edges)),n(),t(Dn(Bn({title:m,status:"success"})))):t(Dn(Bn({title:m,status:"error"}))),a.abort()}catch(p){p&&t(Dn(Bn({title:e("toast.nodesNotValidJSON"),status:"error"})))}},a.readAsText(s),(c=r.current)==null||c.call(r)},[n,t,e]);return i.jsx(hE,{resetRef:r,accept:"application/json",onChange:o,children:s=>i.jsx(Le,{icon:i.jsx(Md,{}),tooltip:e("nodes.loadGraph"),"aria-label":e("nodes.loadGraph"),...s})})},Qae=f.memo(Xae);function Jae(e){const{iconButton:t=!1,...n}=e,r=te(),o=z(Kn),s=Bd(),a=f.useCallback(()=>{r(dd("nodes"))},[r]),{t:c}=be();return nt(["ctrl+enter","meta+enter"],a,{enabled:()=>s,preventDefault:!0,enableOnFormTags:["input","textarea","select"]},[s,o]),i.jsx(Oe,{style:{flexGrow:4},position:"relative",children:i.jsxs(Oe,{style:{position:"relative"},children:[!s&&i.jsx(Oe,{borderRadius:"base",style:{position:"absolute",bottom:"0",left:"0",right:"0",height:"100%",overflow:"clip"},children:i.jsx(xO,{})}),t?i.jsx(Le,{"aria-label":c("parameters.invoke"),type:"submit",icon:i.jsx(y6,{}),isDisabled:!s,onClick:a,flexGrow:1,w:"100%",tooltip:c("parameters.invoke"),tooltipProps:{placement:"bottom"},colorScheme:"accent",id:"invoke-button",_disabled:{background:"none",_hover:{background:"none"}},...n}):i.jsx(rn,{"aria-label":c("parameters.invoke"),type:"submit",isDisabled:!s,onClick:a,flexGrow:1,w:"100%",colorScheme:"accent",id:"invoke-button",fontWeight:700,_disabled:{background:"none",_hover:{background:"none"}},...n,children:"Invoke"})]})})}function Zae(){const{t:e}=be(),t=te(),n=f.useCallback(()=>{t(R7())},[t]);return i.jsx(Le,{icon:i.jsx(hW,{}),tooltip:e("nodes.reloadSchema"),"aria-label":e("nodes.reloadSchema"),onClick:n})}const eie=()=>{const{t:e}=be(),t=z(o=>o.nodes.editorInstance),n=z(o=>o.nodes.nodes),r=f.useCallback(()=>{if(t){const o=t.toObject();o.edges=cs(o.edges,c=>M7(c,["style"]));const s=new Blob([JSON.stringify(o)]),a=document.createElement("a");a.href=URL.createObjectURL(s),a.download="MyNodes.json",document.body.appendChild(a),a.click(),a.remove()}},[t]);return i.jsx(Le,{icon:i.jsx(_m,{}),fontSize:18,tooltip:e("nodes.saveGraph"),"aria-label":e("nodes.saveGraph"),onClick:r,isDisabled:n.length===0})},tie=f.memo(eie),nie=()=>i.jsx(id,{position:"top-center",children:i.jsxs(di,{children:[i.jsx(Jae,{}),i.jsx(Qm,{}),i.jsx(Zae,{}),i.jsx(tie,{}),i.jsx(Qae,{}),i.jsx(Kae,{})]})}),rie=f.memo(nie),oie=fe([Ye],({nodes:e})=>{const t=cs(e.invocationTemplates,n=>({label:n.title,value:n.type,description:n.description}));return t.push({label:"Progress Image",value:"progress_image",description:"Displays the progress image in the Node Editor"}),{data:t}},Ge),sie=()=>{const e=te(),{data:t}=z(oie),n=Pse(),r=Bc(),o=f.useCallback(a=>{const c=n(a);if(!c){r({status:"error",title:`Unknown Invocation type ${a}`});return}e(D7(c))},[e,n,r]),s=f.useCallback(a=>{a&&o(a)},[o]);return i.jsx(H,{sx:{gap:2,alignItems:"center"},children:i.jsx(sr,{selectOnBlur:!1,placeholder:"Add Node",value:null,data:t,maxDropdownHeight:400,nothingFound:"No matching nodes",itemComponent:QO,filter:(a,c)=>c.label.toLowerCase().includes(a.toLowerCase().trim())||c.value.toLowerCase().includes(a.toLowerCase().trim())||c.description.toLowerCase().includes(a.toLowerCase().trim()),onChange:s,sx:{width:"18rem"}})})},QO=f.forwardRef(({label:e,description:t,...n},r)=>i.jsx("div",{ref:r,...n,children:i.jsxs("div",{children:[i.jsx(tt,{fontWeight:600,children:e}),i.jsx(tt,{size:"xs",sx:{color:"base.600",_dark:{color:"base.500"}},children:t})]})}));QO.displayName="SelectItem";const aie=()=>i.jsx(id,{position:"top-left",children:i.jsx(sie,{})}),iie=f.memo(aie),lie=()=>i.jsx(H,{sx:{gap:2,flexDir:"column"},children:cs(e3,({title:e,description:t,color:n},r)=>i.jsx(wn,{label:t,children:i.jsx(pl,{colorScheme:n,sx:{userSelect:"none"},textAlign:"center",children:e})},r))}),cie=f.memo(lie),uie=()=>{const e=z(n=>n),t=T7(e);return i.jsx(Oe,{as:"pre",sx:{fontFamily:"monospace",position:"absolute",top:2,right:2,opacity:.7,p:2,maxHeight:500,maxWidth:500,overflowY:"scroll",borderRadius:"base",bg:"base.200",_dark:{bg:"base.800"}},children:JSON.stringify(t,null,2)})},die=f.memo(uie),fie=()=>{const e=z(n=>n.nodes.shouldShowGraphOverlay),t=z(n=>n.nodes.shouldShowFieldTypeLegend);return i.jsxs(id,{position:"top-right",children:[t&&i.jsx(cie,{}),e&&i.jsx(die,{})]})},pie=f.memo(fie),hie={invocation:XO,progress_image:Bae},mie=()=>{const e=te(),t=z(p=>p.nodes.nodes),n=z(p=>p.nodes.edges),r=f.useCallback(p=>{e(A7(p))},[e]),o=f.useCallback(p=>{e(N7(p))},[e]),s=f.useCallback((p,h)=>{e($7(h))},[e]),a=f.useCallback(p=>{e(z7(p))},[e]),c=f.useCallback(()=>{e(L7())},[e]),d=f.useCallback(p=>{e(B7(p)),p&&p.fitView()},[e]);return i.jsxs(F7,{nodeTypes:hie,nodes:t,edges:n,onNodesChange:r,onEdgesChange:o,onConnectStart:s,onConnect:a,onConnectEnd:c,onInit:d,defaultEdgeOptions:{style:{strokeWidth:2}},children:[i.jsx(iie,{}),i.jsx(rie,{}),i.jsx(pie,{}),i.jsx(Vae,{}),i.jsx(IT,{}),i.jsx(Gae,{})]})},gie=()=>i.jsx(Oe,{layerStyle:"first",sx:{position:"relative",width:"full",height:"full",borderRadius:"base"},children:i.jsx(H7,{children:i.jsx(mie,{})})}),vie=f.memo(gie),bie=()=>i.jsx(vie,{}),yie=f.memo(bie),xie=fe(Ye,({ui:e,generation:t})=>{const{shouldUseSliders:n}=e,{shouldRandomizeSeed:r}=t;return{shouldUseSliders:n,activeLabel:r?void 0:"Manual Seed"}},Ge),wie=()=>{const{shouldUseSliders:e,activeLabel:t}=z(xie);return i.jsx(Oo,{label:"General",activeLabel:t,defaultIsOpen:!0,children:i.jsx(H,{sx:{flexDirection:"column",gap:3},children:e?i.jsxs(i.Fragment,{children:[i.jsx(wi,{}),i.jsx(Ci,{}),i.jsx(xi,{}),i.jsx(Si,{}),i.jsx(Oe,{pt:2,children:i.jsx(ki,{})}),i.jsx(Ic,{})]}):i.jsxs(i.Fragment,{children:[i.jsxs(H,{gap:3,children:[i.jsx(wi,{}),i.jsx(Ci,{}),i.jsx(xi,{})]}),i.jsx(Si,{}),i.jsx(Oe,{pt:2,children:i.jsx(ki,{})}),i.jsx(Ic,{})]})})})},JO=f.memo(wie),ZO=()=>i.jsxs(i.Fragment,{children:[i.jsxs(H,{sx:{flexDirection:"column",gap:2,p:2,borderRadius:4,bg:"base.100",_dark:{bg:"base.850"}},children:[i.jsx(Fd,{}),i.jsx(CO,{}),i.jsx(Ld,{}),i.jsx(SO,{}),i.jsx(wO,{})]}),i.jsx(Hd,{}),i.jsx(JO,{}),i.jsx(kO,{}),i.jsx(zd,{}),i.jsx(Xm,{})]}),e8=()=>i.jsxs(i.Fragment,{children:[i.jsx(Fd,{}),i.jsx(Ld,{}),i.jsx(Hd,{}),i.jsx(JO,{}),i.jsx(Hy,{}),i.jsx(By,{}),i.jsx(zd,{}),i.jsx(Xm,{}),i.jsx(Wy,{}),i.jsx(TO,{}),i.jsx(Fy,{})]}),Sie=()=>{const e=z(t=>t.generation.model);return i.jsxs(H,{sx:{gap:4,w:"full",h:"full"},children:[i.jsx(Ly,{children:e&&e.base_model==="sdxl"?i.jsx(ZO,{}):i.jsx(e8,{})}),i.jsx(MO,{})]})},Cie=f.memo(Sie);var O1={exports:{}};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.Konva=void 0;var n=aw;Object.defineProperty(t,"Konva",{enumerable:!0,get:function(){return n.Konva}});const r=aw;e.exports=r.Konva})(O1,O1.exports);var kie=O1.exports;const ad=cd(kie);var t8={exports:{}};/** + * @license React + * react-reconciler.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var _ie=function(t){var n={},r=f,o=bp,s=Object.assign;function a(l){for(var u="https://reactjs.org/docs/error-decoder.html?invariant="+l,g=1;gZ||C[N]!==j[Z]){var de=` +`+C[N].replace(" at new "," at ");return l.displayName&&de.includes("")&&(de=de.replace("",l.displayName)),de}while(1<=N&&0<=Z);break}}}finally{Gt=!1,Error.prepareStackTrace=g}return(l=l?l.displayName||l.name:"")?Nt(l):""}var Jt=Object.prototype.hasOwnProperty,Vt=[],$e=-1;function yt(l){return{current:l}}function Mt(l){0>$e||(l.current=Vt[$e],Vt[$e]=null,$e--)}function Ht(l,u){$e++,Vt[$e]=l.current,l.current=u}var jn={},Ut=yt(jn),un=yt(!1),sn=jn;function Ir(l,u){var g=l.type.contextTypes;if(!g)return jn;var x=l.stateNode;if(x&&x.__reactInternalMemoizedUnmaskedChildContext===u)return x.__reactInternalMemoizedMaskedChildContext;var C={},j;for(j in g)C[j]=u[j];return x&&(l=l.stateNode,l.__reactInternalMemoizedUnmaskedChildContext=u,l.__reactInternalMemoizedMaskedChildContext=C),C}function Qn(l){return l=l.childContextTypes,l!=null}function It(){Mt(un),Mt(Ut)}function In(l,u,g){if(Ut.current!==jn)throw Error(a(168));Ht(Ut,u),Ht(un,g)}function On(l,u,g){var x=l.stateNode;if(u=u.childContextTypes,typeof x.getChildContext!="function")return g;x=x.getChildContext();for(var C in x)if(!(C in u))throw Error(a(108,M(l)||"Unknown",C));return s({},g,x)}function Jn(l){return l=(l=l.stateNode)&&l.__reactInternalMemoizedMergedChildContext||jn,sn=Ut.current,Ht(Ut,l),Ht(un,un.current),!0}function hr(l,u,g){var x=l.stateNode;if(!x)throw Error(a(169));g?(l=On(l,u,sn),x.__reactInternalMemoizedMergedChildContext=l,Mt(un),Mt(Ut),Ht(Ut,l)):Mt(un),Ht(un,g)}var Tn=Math.clz32?Math.clz32:Sn,An=Math.log,dn=Math.LN2;function Sn(l){return l>>>=0,l===0?32:31-(An(l)/dn|0)|0}var En=64,vn=4194304;function bn(l){switch(l&-l){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return l&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return l&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return l}}function Ke(l,u){var g=l.pendingLanes;if(g===0)return 0;var x=0,C=l.suspendedLanes,j=l.pingedLanes,N=g&268435455;if(N!==0){var Z=N&~C;Z!==0?x=bn(Z):(j&=N,j!==0&&(x=bn(j)))}else N=g&~C,N!==0?x=bn(N):j!==0&&(x=bn(j));if(x===0)return 0;if(u!==0&&u!==x&&!(u&C)&&(C=x&-x,j=u&-u,C>=j||C===16&&(j&4194240)!==0))return u;if(x&4&&(x|=g&16),u=l.entangledLanes,u!==0)for(l=l.entanglements,u&=x;0g;g++)u.push(l);return u}function mt(l,u,g){l.pendingLanes|=u,u!==536870912&&(l.suspendedLanes=0,l.pingedLanes=0),l=l.eventTimes,u=31-Tn(u),l[u]=g}function ot(l,u){var g=l.pendingLanes&~u;l.pendingLanes=u,l.suspendedLanes=0,l.pingedLanes=0,l.expiredLanes&=u,l.mutableReadLanes&=u,l.entangledLanes&=u,u=l.entanglements;var x=l.eventTimes;for(l=l.expirationTimes;0>=N,C-=N,Do=1<<32-Tn(u)+C|g<Cn?(Lr=Xt,Xt=null):Lr=Xt.sibling;var kn=it(ce,Xt,ve[Cn],lt);if(kn===null){Xt===null&&(Xt=Lr);break}l&&Xt&&kn.alternate===null&&u(ce,Xt),ne=j(kn,ne,Cn),nn===null?Tt=kn:nn.sibling=kn,nn=kn,Xt=Lr}if(Cn===ve.length)return g(ce,Xt),Zn&&Ti(ce,Cn),Tt;if(Xt===null){for(;CnCn?(Lr=Xt,Xt=null):Lr=Xt.sibling;var Ja=it(ce,Xt,kn.value,lt);if(Ja===null){Xt===null&&(Xt=Lr);break}l&&Xt&&Ja.alternate===null&&u(ce,Xt),ne=j(Ja,ne,Cn),nn===null?Tt=Ja:nn.sibling=Ja,nn=Ja,Xt=Lr}if(kn.done)return g(ce,Xt),Zn&&Ti(ce,Cn),Tt;if(Xt===null){for(;!kn.done;Cn++,kn=ve.next())kn=Yt(ce,kn.value,lt),kn!==null&&(ne=j(kn,ne,Cn),nn===null?Tt=kn:nn.sibling=kn,nn=kn);return Zn&&Ti(ce,Cn),Tt}for(Xt=x(ce,Xt);!kn.done;Cn++,kn=ve.next())kn=Xn(Xt,ce,Cn,kn.value,lt),kn!==null&&(l&&kn.alternate!==null&&Xt.delete(kn.key===null?Cn:kn.key),ne=j(kn,ne,Cn),nn===null?Tt=kn:nn.sibling=kn,nn=kn);return l&&Xt.forEach(function(X8){return u(ce,X8)}),Zn&&Ti(ce,Cn),Tt}function ga(ce,ne,ve,lt){if(typeof ve=="object"&&ve!==null&&ve.type===h&&ve.key===null&&(ve=ve.props.children),typeof ve=="object"&&ve!==null){switch(ve.$$typeof){case d:e:{for(var Tt=ve.key,nn=ne;nn!==null;){if(nn.key===Tt){if(Tt=ve.type,Tt===h){if(nn.tag===7){g(ce,nn.sibling),ne=C(nn,ve.props.children),ne.return=ce,ce=ne;break e}}else if(nn.elementType===Tt||typeof Tt=="object"&&Tt!==null&&Tt.$$typeof===I&&dx(Tt)===nn.type){g(ce,nn.sibling),ne=C(nn,ve.props),ne.ref=Yc(ce,nn,ve),ne.return=ce,ce=ne;break e}g(ce,nn);break}else u(ce,nn);nn=nn.sibling}ve.type===h?(ne=Fi(ve.props.children,ce.mode,lt,ve.key),ne.return=ce,ce=ne):(lt=_f(ve.type,ve.key,ve.props,null,ce.mode,lt),lt.ref=Yc(ce,ne,ve),lt.return=ce,ce=lt)}return N(ce);case p:e:{for(nn=ve.key;ne!==null;){if(ne.key===nn)if(ne.tag===4&&ne.stateNode.containerInfo===ve.containerInfo&&ne.stateNode.implementation===ve.implementation){g(ce,ne.sibling),ne=C(ne,ve.children||[]),ne.return=ce,ce=ne;break e}else{g(ce,ne);break}else u(ce,ne);ne=ne.sibling}ne=s0(ve,ce.mode,lt),ne.return=ce,ce=ne}return N(ce);case I:return nn=ve._init,ga(ce,ne,nn(ve._payload),lt)}if(q(ve))return $n(ce,ne,ve,lt);if(O(ve))return yo(ce,ne,ve,lt);Jd(ce,ve)}return typeof ve=="string"&&ve!==""||typeof ve=="number"?(ve=""+ve,ne!==null&&ne.tag===6?(g(ce,ne.sibling),ne=C(ne,ve),ne.return=ce,ce=ne):(g(ce,ne),ne=o0(ve,ce.mode,lt),ne.return=ce,ce=ne),N(ce)):g(ce,ne)}return ga}var kl=fx(!0),px=fx(!1),Xc={},Uo=yt(Xc),Qc=yt(Xc),_l=yt(Xc);function Fs(l){if(l===Xc)throw Error(a(174));return l}function bg(l,u){Ht(_l,u),Ht(Qc,l),Ht(Uo,Xc),l=D(u),Mt(Uo),Ht(Uo,l)}function Pl(){Mt(Uo),Mt(Qc),Mt(_l)}function hx(l){var u=Fs(_l.current),g=Fs(Uo.current);u=L(g,l.type,u),g!==u&&(Ht(Qc,l),Ht(Uo,u))}function yg(l){Qc.current===l&&(Mt(Uo),Mt(Qc))}var cr=yt(0);function Zd(l){for(var u=l;u!==null;){if(u.tag===13){var g=u.memoizedState;if(g!==null&&(g=g.dehydrated,g===null||Nr(g)||$s(g)))return u}else if(u.tag===19&&u.memoizedProps.revealOrder!==void 0){if(u.flags&128)return u}else if(u.child!==null){u.child.return=u,u=u.child;continue}if(u===l)break;for(;u.sibling===null;){if(u.return===null||u.return===l)return null;u=u.return}u.sibling.return=u.return,u=u.sibling}return null}var xg=[];function wg(){for(var l=0;lg?g:4,l(!0);var x=Sg.transition;Sg.transition={};try{l(!1),u()}finally{je=g,Sg.transition=x}}function Mx(){return Go().memoizedState}function C8(l,u,g){var x=Ya(l);if(g={lane:x,action:g,hasEagerState:!1,eagerState:null,next:null},Dx(l))Tx(u,g);else if(g=rx(l,u,g,x),g!==null){var C=to();qo(g,l,x,C),Ax(g,u,x)}}function k8(l,u,g){var x=Ya(l),C={lane:x,action:g,hasEagerState:!1,eagerState:null,next:null};if(Dx(l))Tx(u,C);else{var j=l.alternate;if(l.lanes===0&&(j===null||j.lanes===0)&&(j=u.lastRenderedReducer,j!==null))try{var N=u.lastRenderedState,Z=j(N,g);if(C.hasEagerState=!0,C.eagerState=Z,fn(Z,N)){var de=u.interleaved;de===null?(C.next=C,hg(u)):(C.next=de.next,de.next=C),u.interleaved=C;return}}catch{}finally{}g=rx(l,u,C,x),g!==null&&(C=to(),qo(g,l,x,C),Ax(g,u,x))}}function Dx(l){var u=l.alternate;return l===ur||u!==null&&u===ur}function Tx(l,u){Jc=tf=!0;var g=l.pending;g===null?u.next=u:(u.next=g.next,g.next=u),l.pending=u}function Ax(l,u,g){if(g&4194240){var x=u.lanes;x&=l.pendingLanes,g|=x,u.lanes=g,Ee(l,g)}}var of={readContext:Vo,useCallback:Jr,useContext:Jr,useEffect:Jr,useImperativeHandle:Jr,useInsertionEffect:Jr,useLayoutEffect:Jr,useMemo:Jr,useReducer:Jr,useRef:Jr,useState:Jr,useDebugValue:Jr,useDeferredValue:Jr,useTransition:Jr,useMutableSource:Jr,useSyncExternalStore:Jr,useId:Jr,unstable_isNewReconciler:!1},_8={readContext:Vo,useCallback:function(l,u){return Hs().memoizedState=[l,u===void 0?null:u],l},useContext:Vo,useEffect:kx,useImperativeHandle:function(l,u,g){return g=g!=null?g.concat([l]):null,nf(4194308,4,jx.bind(null,u,l),g)},useLayoutEffect:function(l,u){return nf(4194308,4,l,u)},useInsertionEffect:function(l,u){return nf(4,2,l,u)},useMemo:function(l,u){var g=Hs();return u=u===void 0?null:u,l=l(),g.memoizedState=[l,u],l},useReducer:function(l,u,g){var x=Hs();return u=g!==void 0?g(u):u,x.memoizedState=x.baseState=u,l={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:l,lastRenderedState:u},x.queue=l,l=l.dispatch=C8.bind(null,ur,l),[x.memoizedState,l]},useRef:function(l){var u=Hs();return l={current:l},u.memoizedState=l},useState:Sx,useDebugValue:Eg,useDeferredValue:function(l){return Hs().memoizedState=l},useTransition:function(){var l=Sx(!1),u=l[0];return l=S8.bind(null,l[1]),Hs().memoizedState=l,[u,l]},useMutableSource:function(){},useSyncExternalStore:function(l,u,g){var x=ur,C=Hs();if(Zn){if(g===void 0)throw Error(a(407));g=g()}else{if(g=u(),zr===null)throw Error(a(349));Ni&30||vx(x,u,g)}C.memoizedState=g;var j={value:g,getSnapshot:u};return C.queue=j,kx(yx.bind(null,x,j,l),[l]),x.flags|=2048,tu(9,bx.bind(null,x,j,g,u),void 0,null),g},useId:function(){var l=Hs(),u=zr.identifierPrefix;if(Zn){var g=Qr,x=Do;g=(x&~(1<<32-Tn(x)-1)).toString(32)+g,u=":"+u+"R"+g,g=Zc++,0Xg&&(u.flags|=128,x=!0,ou(C,!1),u.lanes=4194304)}else{if(!x)if(l=Zd(j),l!==null){if(u.flags|=128,x=!0,l=l.updateQueue,l!==null&&(u.updateQueue=l,u.flags|=4),ou(C,!0),C.tail===null&&C.tailMode==="hidden"&&!j.alternate&&!Zn)return Zr(u),null}else 2*Ve()-C.renderingStartTime>Xg&&g!==1073741824&&(u.flags|=128,x=!0,ou(C,!1),u.lanes=4194304);C.isBackwards?(j.sibling=u.child,u.child=j):(l=C.last,l!==null?l.sibling=j:u.child=j,C.last=j)}return C.tail!==null?(u=C.tail,C.rendering=u,C.tail=u.sibling,C.renderingStartTime=Ve(),u.sibling=null,l=cr.current,Ht(cr,x?l&1|2:l&1),u):(Zr(u),null);case 22:case 23:return t0(),g=u.memoizedState!==null,l!==null&&l.memoizedState!==null!==g&&(u.flags|=8192),g&&u.mode&1?Ao&1073741824&&(Zr(u),le&&u.subtreeFlags&6&&(u.flags|=8192)):Zr(u),null;case 24:return null;case 25:return null}throw Error(a(156,u.tag))}function D8(l,u){switch(ag(u),u.tag){case 1:return Qn(u.type)&&It(),l=u.flags,l&65536?(u.flags=l&-65537|128,u):null;case 3:return Pl(),Mt(un),Mt(Ut),wg(),l=u.flags,l&65536&&!(l&128)?(u.flags=l&-65537|128,u):null;case 5:return yg(u),null;case 13:if(Mt(cr),l=u.memoizedState,l!==null&&l.dehydrated!==null){if(u.alternate===null)throw Error(a(340));wl()}return l=u.flags,l&65536?(u.flags=l&-65537|128,u):null;case 19:return Mt(cr),null;case 4:return Pl(),null;case 10:return fg(u.type._context),null;case 22:case 23:return t0(),null;case 24:return null;default:return null}}var uf=!1,eo=!1,T8=typeof WeakSet=="function"?WeakSet:Set,pt=null;function Il(l,u){var g=l.ref;if(g!==null)if(typeof g=="function")try{g(null)}catch(x){er(l,u,x)}else g.current=null}function zg(l,u,g){try{g()}catch(x){er(l,u,x)}}var e2=!1;function A8(l,u){for(W(l.containerInfo),pt=u;pt!==null;)if(l=pt,u=l.child,(l.subtreeFlags&1028)!==0&&u!==null)u.return=l,pt=u;else for(;pt!==null;){l=pt;try{var g=l.alternate;if(l.flags&1024)switch(l.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var x=g.memoizedProps,C=g.memoizedState,j=l.stateNode,N=j.getSnapshotBeforeUpdate(l.elementType===l.type?x:ms(l.type,x),C);j.__reactInternalSnapshotBeforeUpdate=N}break;case 3:le&&ln(l.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(a(163))}}catch(Z){er(l,l.return,Z)}if(u=l.sibling,u!==null){u.return=l.return,pt=u;break}pt=l.return}return g=e2,e2=!1,g}function su(l,u,g){var x=u.updateQueue;if(x=x!==null?x.lastEffect:null,x!==null){var C=x=x.next;do{if((C.tag&l)===l){var j=C.destroy;C.destroy=void 0,j!==void 0&&zg(u,g,j)}C=C.next}while(C!==x)}}function df(l,u){if(u=u.updateQueue,u=u!==null?u.lastEffect:null,u!==null){var g=u=u.next;do{if((g.tag&l)===l){var x=g.create;g.destroy=x()}g=g.next}while(g!==u)}}function Lg(l){var u=l.ref;if(u!==null){var g=l.stateNode;switch(l.tag){case 5:l=G(g);break;default:l=g}typeof u=="function"?u(l):u.current=l}}function t2(l){var u=l.alternate;u!==null&&(l.alternate=null,t2(u)),l.child=null,l.deletions=null,l.sibling=null,l.tag===5&&(u=l.stateNode,u!==null&&Ae(u)),l.stateNode=null,l.return=null,l.dependencies=null,l.memoizedProps=null,l.memoizedState=null,l.pendingProps=null,l.stateNode=null,l.updateQueue=null}function n2(l){return l.tag===5||l.tag===3||l.tag===4}function r2(l){e:for(;;){for(;l.sibling===null;){if(l.return===null||n2(l.return))return null;l=l.return}for(l.sibling.return=l.return,l=l.sibling;l.tag!==5&&l.tag!==6&&l.tag!==18;){if(l.flags&2||l.child===null||l.tag===4)continue e;l.child.return=l,l=l.child}if(!(l.flags&2))return l.stateNode}}function Bg(l,u,g){var x=l.tag;if(x===5||x===6)l=l.stateNode,u?Pn(g,l,u):ht(g,l);else if(x!==4&&(l=l.child,l!==null))for(Bg(l,u,g),l=l.sibling;l!==null;)Bg(l,u,g),l=l.sibling}function Fg(l,u,g){var x=l.tag;if(x===5||x===6)l=l.stateNode,u?qe(g,l,u):xe(g,l);else if(x!==4&&(l=l.child,l!==null))for(Fg(l,u,g),l=l.sibling;l!==null;)Fg(l,u,g),l=l.sibling}var Ur=null,gs=!1;function Vs(l,u,g){for(g=g.child;g!==null;)Hg(l,u,g),g=g.sibling}function Hg(l,u,g){if(gn&&typeof gn.onCommitFiberUnmount=="function")try{gn.onCommitFiberUnmount(Yn,g)}catch{}switch(g.tag){case 5:eo||Il(g,u);case 6:if(le){var x=Ur,C=gs;Ur=null,Vs(l,u,g),Ur=x,gs=C,Ur!==null&&(gs?Je(Ur,g.stateNode):Pe(Ur,g.stateNode))}else Vs(l,u,g);break;case 18:le&&Ur!==null&&(gs?Be(Ur,g.stateNode):xt(Ur,g.stateNode));break;case 4:le?(x=Ur,C=gs,Ur=g.stateNode.containerInfo,gs=!0,Vs(l,u,g),Ur=x,gs=C):(ge&&(x=g.stateNode.containerInfo,C=br(x),Wn(x,C)),Vs(l,u,g));break;case 0:case 11:case 14:case 15:if(!eo&&(x=g.updateQueue,x!==null&&(x=x.lastEffect,x!==null))){C=x=x.next;do{var j=C,N=j.destroy;j=j.tag,N!==void 0&&(j&2||j&4)&&zg(g,u,N),C=C.next}while(C!==x)}Vs(l,u,g);break;case 1:if(!eo&&(Il(g,u),x=g.stateNode,typeof x.componentWillUnmount=="function"))try{x.props=g.memoizedProps,x.state=g.memoizedState,x.componentWillUnmount()}catch(Z){er(g,u,Z)}Vs(l,u,g);break;case 21:Vs(l,u,g);break;case 22:g.mode&1?(eo=(x=eo)||g.memoizedState!==null,Vs(l,u,g),eo=x):Vs(l,u,g);break;default:Vs(l,u,g)}}function o2(l){var u=l.updateQueue;if(u!==null){l.updateQueue=null;var g=l.stateNode;g===null&&(g=l.stateNode=new T8),u.forEach(function(x){var C=V8.bind(null,l,x);g.has(x)||(g.add(x),x.then(C,C))})}}function vs(l,u){var g=u.deletions;if(g!==null)for(var x=0;x";case pf:return":has("+(Ug(l)||"")+")";case hf:return'[role="'+l.value+'"]';case gf:return'"'+l.value+'"';case mf:return'[data-testname="'+l.value+'"]';default:throw Error(a(365))}}function u2(l,u){var g=[];l=[l,0];for(var x=0;xC&&(C=N),x&=~j}if(x=C,x=Ve()-x,x=(120>x?120:480>x?480:1080>x?1080:1920>x?1920:3e3>x?3e3:4320>x?4320:1960*$8(x/1960))-x,10l?16:l,Ka===null)var x=!1;else{if(l=Ka,Ka=null,wf=0,an&6)throw Error(a(331));var C=an;for(an|=4,pt=l.current;pt!==null;){var j=pt,N=j.child;if(pt.flags&16){var Z=j.deletions;if(Z!==null){for(var de=0;deVe()-Yg?zi(l,0):Kg|=g),bo(l,u)}function y2(l,u){u===0&&(l.mode&1?(u=vn,vn<<=1,!(vn&130023424)&&(vn=4194304)):u=1);var g=to();l=Bs(l,u),l!==null&&(mt(l,u,g),bo(l,g))}function W8(l){var u=l.memoizedState,g=0;u!==null&&(g=u.retryLane),y2(l,g)}function V8(l,u){var g=0;switch(l.tag){case 13:var x=l.stateNode,C=l.memoizedState;C!==null&&(g=C.retryLane);break;case 19:x=l.stateNode;break;default:throw Error(a(314))}x!==null&&x.delete(u),y2(l,g)}var x2;x2=function(l,u,g){if(l!==null)if(l.memoizedProps!==u.pendingProps||un.current)go=!0;else{if(!(l.lanes&g)&&!(u.flags&128))return go=!1,R8(l,u,g);go=!!(l.flags&131072)}else go=!1,Zn&&u.flags&1048576&&Qy(u,io,u.index);switch(u.lanes=0,u.tag){case 2:var x=u.type;af(l,u),l=u.pendingProps;var C=Ir(u,Ut.current);Cl(u,g),C=kg(null,u,x,l,C,g);var j=_g();return u.flags|=1,typeof C=="object"&&C!==null&&typeof C.render=="function"&&C.$$typeof===void 0?(u.tag=1,u.memoizedState=null,u.updateQueue=null,Qn(x)?(j=!0,Jn(u)):j=!1,u.memoizedState=C.state!==null&&C.state!==void 0?C.state:null,mg(u),C.updater=Qd,u.stateNode=C,C._reactInternals=u,vg(u,x,l,g),u=Dg(null,u,x,!0,j,g)):(u.tag=0,Zn&&j&&sg(u),uo(null,u,C,g),u=u.child),u;case 16:x=u.elementType;e:{switch(af(l,u),l=u.pendingProps,C=x._init,x=C(x._payload),u.type=x,C=u.tag=G8(x),l=ms(x,l),C){case 0:u=Mg(null,u,x,l,g);break e;case 1:u=Gx(null,u,x,l,g);break e;case 11:u=Fx(null,u,x,l,g);break e;case 14:u=Hx(null,u,x,ms(x.type,l),g);break e}throw Error(a(306,x,""))}return u;case 0:return x=u.type,C=u.pendingProps,C=u.elementType===x?C:ms(x,C),Mg(l,u,x,C,g);case 1:return x=u.type,C=u.pendingProps,C=u.elementType===x?C:ms(x,C),Gx(l,u,x,C,g);case 3:e:{if(qx(u),l===null)throw Error(a(387));x=u.pendingProps,j=u.memoizedState,C=j.element,ox(l,u),Xd(u,x,null,g);var N=u.memoizedState;if(x=N.element,_e&&j.isDehydrated)if(j={element:x,isDehydrated:!1,cache:N.cache,pendingSuspenseBoundaries:N.pendingSuspenseBoundaries,transitions:N.transitions},u.updateQueue.baseState=j,u.memoizedState=j,u.flags&256){C=jl(Error(a(423)),u),u=Kx(l,u,x,g,C);break e}else if(x!==C){C=jl(Error(a(424)),u),u=Kx(l,u,x,g,C);break e}else for(_e&&(Wo=ee(u.stateNode.containerInfo),To=u,Zn=!0,hs=null,Kc=!1),g=px(u,null,x,g),u.child=g;g;)g.flags=g.flags&-3|4096,g=g.sibling;else{if(wl(),x===C){u=ha(l,u,g);break e}uo(l,u,x,g)}u=u.child}return u;case 5:return hx(u),l===null&&lg(u),x=u.type,C=u.pendingProps,j=l!==null?l.memoizedProps:null,N=C.children,K(x,C)?N=null:j!==null&&K(x,j)&&(u.flags|=32),Ux(l,u),uo(l,u,N,g),u.child;case 6:return l===null&&lg(u),null;case 13:return Yx(l,u,g);case 4:return bg(u,u.stateNode.containerInfo),x=u.pendingProps,l===null?u.child=kl(u,null,x,g):uo(l,u,x,g),u.child;case 11:return x=u.type,C=u.pendingProps,C=u.elementType===x?C:ms(x,C),Fx(l,u,x,C,g);case 7:return uo(l,u,u.pendingProps,g),u.child;case 8:return uo(l,u,u.pendingProps.children,g),u.child;case 12:return uo(l,u,u.pendingProps.children,g),u.child;case 10:e:{if(x=u.type._context,C=u.pendingProps,j=u.memoizedProps,N=C.value,nx(u,x,N),j!==null)if(fn(j.value,N)){if(j.children===C.children&&!un.current){u=ha(l,u,g);break e}}else for(j=u.child,j!==null&&(j.return=u);j!==null;){var Z=j.dependencies;if(Z!==null){N=j.child;for(var de=Z.firstContext;de!==null;){if(de.context===x){if(j.tag===1){de=pa(-1,g&-g),de.tag=2;var De=j.updateQueue;if(De!==null){De=De.shared;var gt=De.pending;gt===null?de.next=de:(de.next=gt.next,gt.next=de),De.pending=de}}j.lanes|=g,de=j.alternate,de!==null&&(de.lanes|=g),pg(j.return,g,u),Z.lanes|=g;break}de=de.next}}else if(j.tag===10)N=j.type===u.type?null:j.child;else if(j.tag===18){if(N=j.return,N===null)throw Error(a(341));N.lanes|=g,Z=N.alternate,Z!==null&&(Z.lanes|=g),pg(N,g,u),N=j.sibling}else N=j.child;if(N!==null)N.return=j;else for(N=j;N!==null;){if(N===u){N=null;break}if(j=N.sibling,j!==null){j.return=N.return,N=j;break}N=N.return}j=N}uo(l,u,C.children,g),u=u.child}return u;case 9:return C=u.type,x=u.pendingProps.children,Cl(u,g),C=Vo(C),x=x(C),u.flags|=1,uo(l,u,x,g),u.child;case 14:return x=u.type,C=ms(x,u.pendingProps),C=ms(x.type,C),Hx(l,u,x,C,g);case 15:return Wx(l,u,u.type,u.pendingProps,g);case 17:return x=u.type,C=u.pendingProps,C=u.elementType===x?C:ms(x,C),af(l,u),u.tag=1,Qn(x)?(l=!0,Jn(u)):l=!1,Cl(u,g),cx(u,x,C),vg(u,x,C,g),Dg(null,u,x,!0,l,g);case 19:return Qx(l,u,g);case 22:return Vx(l,u,g)}throw Error(a(156,u.tag))};function w2(l,u){return We(l,u)}function U8(l,u,g,x){this.tag=l,this.key=g,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=u,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=x,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ko(l,u,g,x){return new U8(l,u,g,x)}function r0(l){return l=l.prototype,!(!l||!l.isReactComponent)}function G8(l){if(typeof l=="function")return r0(l)?1:0;if(l!=null){if(l=l.$$typeof,l===y)return 11;if(l===_)return 14}return 2}function Qa(l,u){var g=l.alternate;return g===null?(g=Ko(l.tag,u,l.key,l.mode),g.elementType=l.elementType,g.type=l.type,g.stateNode=l.stateNode,g.alternate=l,l.alternate=g):(g.pendingProps=u,g.type=l.type,g.flags=0,g.subtreeFlags=0,g.deletions=null),g.flags=l.flags&14680064,g.childLanes=l.childLanes,g.lanes=l.lanes,g.child=l.child,g.memoizedProps=l.memoizedProps,g.memoizedState=l.memoizedState,g.updateQueue=l.updateQueue,u=l.dependencies,g.dependencies=u===null?null:{lanes:u.lanes,firstContext:u.firstContext},g.sibling=l.sibling,g.index=l.index,g.ref=l.ref,g}function _f(l,u,g,x,C,j){var N=2;if(x=l,typeof l=="function")r0(l)&&(N=1);else if(typeof l=="string")N=5;else e:switch(l){case h:return Fi(g.children,C,j,u);case m:N=8,C|=8;break;case v:return l=Ko(12,g,u,C|2),l.elementType=v,l.lanes=j,l;case S:return l=Ko(13,g,u,C),l.elementType=S,l.lanes=j,l;case k:return l=Ko(19,g,u,C),l.elementType=k,l.lanes=j,l;case P:return Pf(g,C,j,u);default:if(typeof l=="object"&&l!==null)switch(l.$$typeof){case b:N=10;break e;case w:N=9;break e;case y:N=11;break e;case _:N=14;break e;case I:N=16,x=null;break e}throw Error(a(130,l==null?l:typeof l,""))}return u=Ko(N,g,u,C),u.elementType=l,u.type=x,u.lanes=j,u}function Fi(l,u,g,x){return l=Ko(7,l,x,u),l.lanes=g,l}function Pf(l,u,g,x){return l=Ko(22,l,x,u),l.elementType=P,l.lanes=g,l.stateNode={isHidden:!1},l}function o0(l,u,g){return l=Ko(6,l,null,u),l.lanes=g,l}function s0(l,u,g){return u=Ko(4,l.children!==null?l.children:[],l.key,u),u.lanes=g,u.stateNode={containerInfo:l.containerInfo,pendingChildren:null,implementation:l.implementation},u}function q8(l,u,g,x,C){this.tag=u,this.containerInfo=l,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=oe,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Bt(0),this.expirationTimes=Bt(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Bt(0),this.identifierPrefix=x,this.onRecoverableError=C,_e&&(this.mutableSourceEagerHydrationData=null)}function S2(l,u,g,x,C,j,N,Z,de){return l=new q8(l,u,g,Z,de),u===1?(u=1,j===!0&&(u|=8)):u=0,j=Ko(3,null,null,u),l.current=j,j.stateNode=l,j.memoizedState={element:x,isDehydrated:g,cache:null,transitions:null,pendingSuspenseBoundaries:null},mg(j),l}function C2(l){if(!l)return jn;l=l._reactInternals;e:{if(T(l)!==l||l.tag!==1)throw Error(a(170));var u=l;do{switch(u.tag){case 3:u=u.stateNode.context;break e;case 1:if(Qn(u.type)){u=u.stateNode.__reactInternalMemoizedMergedChildContext;break e}}u=u.return}while(u!==null);throw Error(a(171))}if(l.tag===1){var g=l.type;if(Qn(g))return On(l,g,u)}return u}function k2(l){var u=l._reactInternals;if(u===void 0)throw typeof l.render=="function"?Error(a(188)):(l=Object.keys(l).join(","),Error(a(268,l)));return l=Q(u),l===null?null:l.stateNode}function _2(l,u){if(l=l.memoizedState,l!==null&&l.dehydrated!==null){var g=l.retryLane;l.retryLane=g!==0&&g=De&&j>=Yt&&C<=gt&&N<=it){l.splice(u,1);break}else if(x!==De||g.width!==de.width||itN){if(!(j!==Yt||g.height!==de.height||gtC)){De>x&&(de.width+=De-x,de.x=x),gtj&&(de.height+=Yt-j,de.y=j),itg&&(g=N)),N ")+` + +No matching component was found for: + `)+l.join(" > ")}return null},n.getPublicRootInstance=function(l){if(l=l.current,!l.child)return null;switch(l.child.tag){case 5:return G(l.child.stateNode);default:return l.child.stateNode}},n.injectIntoDevTools=function(l){if(l={bundleType:l.bundleType,version:l.version,rendererPackageName:l.rendererPackageName,rendererConfig:l.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:c.ReactCurrentDispatcher,findHostInstanceByFiber:K8,findFiberByHostInstance:l.findFiberByHostInstance||Y8,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.2.0"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")l=!1;else{var u=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(u.isDisabled||!u.supportsFiber)l=!0;else{try{Yn=u.inject(l),gn=u}catch{}l=!!u.checkDCE}}return l},n.isAlreadyRendering=function(){return!1},n.observeVisibleRects=function(l,u,g,x){if(!ct)throw Error(a(363));l=Gg(l,u);var C=At(l,g,x).disconnect;return{disconnect:function(){C()}}},n.registerMutableSourceForHydration=function(l,u){var g=u._getVersion;g=g(u._source),l.mutableSourceEagerHydrationData==null?l.mutableSourceEagerHydrationData=[u,g]:l.mutableSourceEagerHydrationData.push(u,g)},n.runWithPriority=function(l,u){var g=je;try{return je=l,u()}finally{je=g}},n.shouldError=function(){return null},n.shouldSuspend=function(){return!1},n.updateContainer=function(l,u,g,x){var C=u.current,j=to(),N=Ya(C);return g=C2(g),u.context===null?u.context=g:u.pendingContext=g,u=pa(j,N),u.payload={element:l},x=x===void 0?null:x,x!==null&&(u.callback=x),l=Ga(C,u,N),l!==null&&(qo(l,C,N,j),Yd(l,C,N)),N},n};t8.exports=_ie;var Pie=t8.exports;const jie=cd(Pie);var n8={exports:{}},xl={};/** + * @license React + * react-reconciler-constants.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */xl.ConcurrentRoot=1;xl.ContinuousEventPriority=4;xl.DefaultEventPriority=16;xl.DiscreteEventPriority=1;xl.IdleEventPriority=536870912;xl.LegacyRoot=0;n8.exports=xl;var r8=n8.exports;const n_={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let r_=!1,o_=!1;const Ky=".react-konva-event",Iie=`ReactKonva: You have a Konva node with draggable = true and position defined but no onDragMove or onDragEnd events are handled. +Position of a node will be changed during drag&drop, so you should update state of the react app as well. +Consider to add onDragMove or onDragEnd events. +For more info see: https://github.com/konvajs/react-konva/issues/256 +`,Eie=`ReactKonva: You are using "zIndex" attribute for a Konva node. +react-konva may get confused with ordering. Just define correct order of elements in your render function of a component. +For more info see: https://github.com/konvajs/react-konva/issues/194 +`,Oie={};function og(e,t,n=Oie){if(!r_&&"zIndex"in t&&(console.warn(Eie),r_=!0),!o_&&t.draggable){var r=t.x!==void 0||t.y!==void 0,o=t.onDragEnd||t.onDragMove;r&&!o&&(console.warn(Iie),o_=!0)}for(var s in n)if(!n_[s]){var a=s.slice(0,2)==="on",c=n[s]!==t[s];if(a&&c){var d=s.substr(2).toLowerCase();d.substr(0,7)==="content"&&(d="content"+d.substr(7,1).toUpperCase()+d.substr(8)),e.off(d,n[s])}var p=!t.hasOwnProperty(s);p&&e.setAttr(s,void 0)}var h=t._useStrictMode,m={},v=!1;const b={};for(var s in t)if(!n_[s]){var a=s.slice(0,2)==="on",w=n[s]!==t[s];if(a&&w){var d=s.substr(2).toLowerCase();d.substr(0,7)==="content"&&(d="content"+d.substr(7,1).toUpperCase()+d.substr(8)),t[s]&&(b[d]=t[s])}!a&&(t[s]!==n[s]||h&&t[s]!==e.getAttr(s))&&(v=!0,m[s]=t[s])}v&&(e.setAttrs(m),Di(e));for(var d in b)e.on(d+Ky,b[d])}function Di(e){if(!W7.Konva.autoDrawEnabled){var t=e.getLayer()||e.getStage();t&&t.batchDraw()}}const o8={},Rie={};ad.Node.prototype._applyProps=og;function Mie(e,t){if(typeof t=="string"){console.error(`Do not use plain text as child of Konva.Node. You are using text: ${t}`);return}e.add(t),Di(e)}function Die(e,t,n){let r=ad[e];r||(console.error(`Konva has no node with the type ${e}. Group will be used instead. If you use minimal version of react-konva, just import required nodes into Konva: "import "konva/lib/shapes/${e}" If you want to render DOM elements as part of canvas tree take a look into this demo: https://konvajs.github.io/docs/react/DOM_Portal.html`),r=ad.Group);const o={},s={};for(var a in t){var c=a.slice(0,2)==="on";c?s[a]=t[a]:o[a]=t[a]}const d=new r(o);return og(d,s),d}function Tie(e,t,n){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${e}"`)}function Aie(e,t,n){return!1}function Nie(e){return e}function $ie(){return null}function zie(){return null}function Lie(e,t,n,r){return Rie}function Bie(){}function Fie(e){}function Hie(e,t){return!1}function Wie(){return o8}function Vie(){return o8}const Uie=setTimeout,Gie=clearTimeout,qie=-1;function Kie(e,t){return!1}const Yie=!1,Xie=!0,Qie=!0;function Jie(e,t){t.parent===e?t.moveToTop():e.add(t),Di(e)}function Zie(e,t){t.parent===e?t.moveToTop():e.add(t),Di(e)}function s8(e,t,n){t._remove(),e.add(t),t.setZIndex(n.getZIndex()),Di(e)}function ele(e,t,n){s8(e,t,n)}function tle(e,t){t.destroy(),t.off(Ky),Di(e)}function nle(e,t){t.destroy(),t.off(Ky),Di(e)}function rle(e,t,n){console.error(`Text components are not yet supported in ReactKonva. You text is: "${n}"`)}function ole(e,t,n){}function sle(e,t,n,r,o){og(e,o,r)}function ale(e){e.hide(),Di(e)}function ile(e){}function lle(e,t){(t.visible==null||t.visible)&&e.show()}function cle(e,t){}function ule(e){}function dle(){}const fle=()=>r8.DefaultEventPriority,ple=Object.freeze(Object.defineProperty({__proto__:null,appendChild:Jie,appendChildToContainer:Zie,appendInitialChild:Mie,cancelTimeout:Gie,clearContainer:ule,commitMount:ole,commitTextUpdate:rle,commitUpdate:sle,createInstance:Die,createTextInstance:Tie,detachDeletedInstance:dle,finalizeInitialChildren:Aie,getChildHostContext:Vie,getCurrentEventPriority:fle,getPublicInstance:Nie,getRootHostContext:Wie,hideInstance:ale,hideTextInstance:ile,idlePriority:bp.unstable_IdlePriority,insertBefore:s8,insertInContainerBefore:ele,isPrimaryRenderer:Yie,noTimeout:qie,now:bp.unstable_now,prepareForCommit:$ie,preparePortalMount:zie,prepareUpdate:Lie,removeChild:tle,removeChildFromContainer:nle,resetAfterCommit:Bie,resetTextContent:Fie,run:bp.unstable_runWithPriority,scheduleTimeout:Uie,shouldDeprioritizeSubtree:Hie,shouldSetTextContent:Kie,supportsMutation:Qie,unhideInstance:lle,unhideTextInstance:cle,warnsIfNotActing:Xie},Symbol.toStringTag,{value:"Module"}));var hle=Object.defineProperty,mle=Object.defineProperties,gle=Object.getOwnPropertyDescriptors,s_=Object.getOwnPropertySymbols,vle=Object.prototype.hasOwnProperty,ble=Object.prototype.propertyIsEnumerable,a_=(e,t,n)=>t in e?hle(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,i_=(e,t)=>{for(var n in t||(t={}))vle.call(t,n)&&a_(e,n,t[n]);if(s_)for(var n of s_(t))ble.call(t,n)&&a_(e,n,t[n]);return e},yle=(e,t)=>mle(e,gle(t));function a8(e,t,n){if(!e)return;if(n(e)===!0)return e;let r=t?e.return:e.child;for(;r;){const o=a8(r,t,n);if(o)return o;r=t?null:r.sibling}}function i8(e){try{return Object.defineProperties(e,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return e}}const Yy=i8(f.createContext(null));class l8 extends f.Component{render(){return f.createElement(Yy.Provider,{value:this._reactInternals},this.props.children)}}const{ReactCurrentOwner:l_,ReactCurrentDispatcher:c_}=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function xle(){const e=f.useContext(Yy);if(e===null)throw new Error("its-fine: useFiber must be called within a !");const t=f.useId();return f.useMemo(()=>{for(const r of[l_==null?void 0:l_.current,e,e==null?void 0:e.alternate]){if(!r)continue;const o=a8(r,!1,s=>{let a=s.memoizedState;for(;a;){if(a.memoizedState===t)return!0;a=a.next}});if(o)return o}},[e,t])}function wle(){var e,t;const n=xle(),[r]=f.useState(()=>new Map);r.clear();let o=n;for(;o;){const s=(e=o.type)==null?void 0:e._context;s&&s!==Yy&&!r.has(s)&&r.set(s,(t=c_==null?void 0:c_.current)==null?void 0:t.readContext(i8(s))),o=o.return}return r}function Sle(){const e=wle();return f.useMemo(()=>Array.from(e.keys()).reduce((t,n)=>r=>f.createElement(t,null,f.createElement(n.Provider,yle(i_({},r),{value:e.get(n)}))),t=>f.createElement(l8,i_({},t))),[e])}function Cle(e){const t=F.useRef({});return F.useLayoutEffect(()=>{t.current=e}),F.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const kle=e=>{const t=F.useRef(),n=F.useRef(),r=F.useRef(),o=Cle(e),s=Sle(),a=c=>{const{forwardedRef:d}=e;d&&(typeof d=="function"?d(c):d.current=c)};return F.useLayoutEffect(()=>(n.current=new ad.Stage({width:e.width,height:e.height,container:t.current}),a(n.current),r.current=Ou.createContainer(n.current,r8.LegacyRoot,!1,null),Ou.updateContainer(F.createElement(s,{},e.children),r.current),()=>{ad.isBrowser&&(a(null),Ou.updateContainer(null,r.current,null),n.current.destroy())}),[]),F.useLayoutEffect(()=>{a(n.current),og(n.current,e,o),Ou.updateContainer(F.createElement(s,{},e.children),r.current,null)}),F.createElement("div",{ref:t,id:e.id,accessKey:e.accessKey,className:e.className,role:e.role,style:e.style,tabIndex:e.tabIndex,title:e.title})},yu="Layer",Na="Group",aa="Rect",Hi="Circle",Yh="Line",c8="Image",_le="Transformer",Ou=jie(ple);Ou.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:F.version,rendererPackageName:"react-konva"});const Ple=F.forwardRef((e,t)=>F.createElement(l8,{},F.createElement(kle,{...e,forwardedRef:t}))),jle=fe([mn,ir],(e,t)=>{const{tool:n,isMovingBoundingBox:r}=e;return{tool:n,isStaging:t,isMovingBoundingBox:r}},{memoizeOptions:{resultEqualityCheck:Qt}}),Ile=()=>{const e=te(),{tool:t,isStaging:n,isMovingBoundingBox:r}=z(jle);return{handleDragStart:f.useCallback(()=>{(t==="move"||n)&&!r&&e(Ap(!0))},[e,r,n,t]),handleDragMove:f.useCallback(o=>{if(!((t==="move"||n)&&!r))return;const s={x:o.target.x(),y:o.target.y()};e(n3(s))},[e,r,n,t]),handleDragEnd:f.useCallback(()=>{(t==="move"||n)&&!r&&e(Ap(!1))},[e,r,n,t])}},Ele=fe([mn,Kn,ir],(e,t,n)=>{const{cursorPosition:r,shouldLockBoundingBox:o,shouldShowBoundingBox:s,tool:a,isMaskEnabled:c,shouldSnapToGrid:d}=e;return{activeTabName:t,isCursorOnCanvas:!!r,shouldLockBoundingBox:o,shouldShowBoundingBox:s,tool:a,isStaging:n,isMaskEnabled:c,shouldSnapToGrid:d}},{memoizeOptions:{resultEqualityCheck:Qt}}),Ole=()=>{const e=te(),{activeTabName:t,shouldShowBoundingBox:n,tool:r,isStaging:o,isMaskEnabled:s,shouldSnapToGrid:a}=z(Ele),c=f.useRef(null),d=r3(),p=()=>e(q1());nt(["shift+c"],()=>{p()},{enabled:()=>!o,preventDefault:!0},[]);const h=()=>e(pd(!s));nt(["h"],()=>{h()},{enabled:()=>!o,preventDefault:!0},[s]),nt(["n"],()=>{e(Wu(!a))},{enabled:!0,preventDefault:!0},[a]),nt("esc",()=>{e(V7())},{enabled:()=>!0,preventDefault:!0}),nt("shift+h",()=>{e(U7(!n))},{enabled:()=>!o,preventDefault:!0},[t,n]),nt(["space"],m=>{m.repeat||(d==null||d.container().focus(),r!=="move"&&(c.current=r,e(ea("move"))),r==="move"&&c.current&&c.current!=="move"&&(e(ea(c.current)),c.current="move"))},{keyup:!0,keydown:!0,preventDefault:!0},[r,c])},Xy=e=>{const t=e.getPointerPosition(),n=e.getAbsoluteTransform().copy();if(!t||!n)return;const r=n.invert().point(t);return{x:r.x,y:r.y}},u8=()=>{const e=te(),t=Ia(),n=r3();return{updateColorUnderCursor:()=>{if(!n||!t)return;const r=n.getPointerPosition();if(!r)return;const o=G7.pixelRatio,[s,a,c,d]=t.getContext().getImageData(r.x*o,r.y*o,1,1).data;e(q7({r:s,g:a,b:c,a:d}))},commitColorUnderCursor:()=>{e(K7())}}},Rle=fe([Kn,mn,ir],(e,t,n)=>{const{tool:r}=t;return{tool:r,activeTabName:e,isStaging:n}},{memoizeOptions:{resultEqualityCheck:Qt}}),Mle=e=>{const t=te(),{tool:n,isStaging:r}=z(Rle),{commitColorUnderCursor:o}=u8();return f.useCallback(s=>{if(!e.current)return;if(e.current.container().focus(),n==="move"||r){t(Ap(!0));return}if(n==="colorPicker"){o();return}const a=Xy(e.current);a&&(s.evt.preventDefault(),t(o3(!0)),t(Y7([a.x,a.y])))},[e,n,r,t,o])},Dle=fe([Kn,mn,ir],(e,t,n)=>{const{tool:r,isDrawing:o}=t;return{tool:r,isDrawing:o,activeTabName:e,isStaging:n}},{memoizeOptions:{resultEqualityCheck:Qt}}),Tle=(e,t,n)=>{const r=te(),{isDrawing:o,tool:s,isStaging:a}=z(Dle),{updateColorUnderCursor:c}=u8();return f.useCallback(()=>{if(!e.current)return;const d=Xy(e.current);if(d){if(r(X7(d)),n.current=d,s==="colorPicker"){c();return}!o||s==="move"||a||(t.current=!0,r(s3([d.x,d.y])))}},[t,r,o,a,n,e,s,c])},Ale=()=>{const e=te();return f.useCallback(()=>{e(Q7())},[e])},Nle=fe([Kn,mn,ir],(e,t,n)=>{const{tool:r,isDrawing:o}=t;return{tool:r,isDrawing:o,activeTabName:e,isStaging:n}},{memoizeOptions:{resultEqualityCheck:Qt}}),$le=(e,t)=>{const n=te(),{tool:r,isDrawing:o,isStaging:s}=z(Nle);return f.useCallback(()=>{if(r==="move"||s){n(Ap(!1));return}if(!t.current&&o&&e.current){const a=Xy(e.current);if(!a)return;n(s3([a.x,a.y]))}else t.current=!1;n(o3(!1))},[t,n,o,s,e,r])},zle=fe([mn],e=>{const{isMoveStageKeyHeld:t,stageScale:n}=e;return{isMoveStageKeyHeld:t,stageScale:n}},{memoizeOptions:{resultEqualityCheck:Qt}}),Lle=e=>{const t=te(),{isMoveStageKeyHeld:n,stageScale:r}=z(zle);return f.useCallback(o=>{if(!e.current||n)return;o.evt.preventDefault();const s=e.current.getPointerPosition();if(!s)return;const a={x:(s.x-e.current.x())/r,y:(s.y-e.current.y())/r};let c=o.evt.deltaY;o.evt.ctrlKey&&(c=-c);const d=Es(r*eD**c,Z7,J7),p={x:s.x-a.x*d,y:s.y-a.y*d};t(tD(d)),t(n3(p))},[e,n,r,t])},Ble=fe(mn,e=>{const{boundingBoxCoordinates:t,boundingBoxDimensions:n,stageDimensions:r,stageScale:o,shouldDarkenOutsideBoundingBox:s,stageCoordinates:a}=e;return{boundingBoxCoordinates:t,boundingBoxDimensions:n,shouldDarkenOutsideBoundingBox:s,stageCoordinates:a,stageDimensions:r,stageScale:o}},{memoizeOptions:{resultEqualityCheck:Qt}}),Fle=()=>{const{boundingBoxCoordinates:e,boundingBoxDimensions:t,shouldDarkenOutsideBoundingBox:n,stageCoordinates:r,stageDimensions:o,stageScale:s}=z(Ble);return i.jsxs(Na,{children:[i.jsx(aa,{offsetX:r.x/s,offsetY:r.y/s,height:o.height/s,width:o.width/s,fill:"rgba(0,0,0,0.4)",listening:!1,visible:n}),i.jsx(aa,{x:e.x,y:e.y,width:t.width,height:t.height,fill:"rgb(255,255,255)",listening:!1,visible:n,globalCompositeOperation:"destination-out"})]})},Hle=fe([mn],e=>{const{stageScale:t,stageCoordinates:n,stageDimensions:r}=e;return{stageScale:t,stageCoordinates:n,stageDimensions:r}},{memoizeOptions:{resultEqualityCheck:Qt}}),Wle=()=>{const{stageScale:e,stageCoordinates:t,stageDimensions:n}=z(Hle),{colorMode:r}=Ds(),[o,s]=f.useState([]),[a,c]=Dc("colors",["base.800","base.200"]),d=f.useCallback(p=>p/e,[e]);return f.useLayoutEffect(()=>{const{width:p,height:h}=n,{x:m,y:v}=t,b={x1:0,y1:0,x2:p,y2:h,offset:{x:d(m),y:d(v)}},w={x:Math.ceil(d(m)/64)*64,y:Math.ceil(d(v)/64)*64},y={x1:-w.x,y1:-w.y,x2:d(p)-w.x+64,y2:d(h)-w.y+64},k={x1:Math.min(b.x1,y.x1),y1:Math.min(b.y1,y.y1),x2:Math.max(b.x2,y.x2),y2:Math.max(b.y2,y.y2)},_=k.x2-k.x1,I=k.y2-k.y1,P=Math.round(_/64)+1,E=Math.round(I/64)+1,O=vw(0,P).map(M=>i.jsx(Yh,{x:k.x1+M*64,y:k.y1,points:[0,0,0,I],stroke:r==="dark"?a:c,strokeWidth:1},`x_${M}`)),R=vw(0,E).map(M=>i.jsx(Yh,{x:k.x1,y:k.y1+M*64,points:[0,0,_,0],stroke:r==="dark"?a:c,strokeWidth:1},`y_${M}`));s(O.concat(R))},[e,t,n,d,r,a,c]),i.jsx(Na,{children:o})},Vle=fe([mo,mn],(e,t)=>{const{progressImage:n,sessionId:r}=e,{sessionId:o,boundingBox:s}=t.layerState.stagingArea;return{boundingBox:s,progressImage:r===o?n:void 0}},{memoizeOptions:{resultEqualityCheck:Qt}}),Ule=e=>{const{...t}=e,{progressImage:n,boundingBox:r}=z(Vle),[o,s]=f.useState(null);return f.useEffect(()=>{if(!n)return;const a=new Image;a.onload=()=>{s(a)},a.src=n.dataURL},[n]),n&&r&&o?i.jsx(c8,{x:r.x,y:r.y,width:r.width,height:r.height,image:o,listening:!1,...t}):null},tl=e=>{const{r:t,g:n,b:r,a:o}=e;return`rgba(${t}, ${n}, ${r}, ${o})`},Gle=fe(mn,e=>{const{maskColor:t,stageCoordinates:n,stageDimensions:r,stageScale:o}=e;return{stageCoordinates:n,stageDimensions:r,stageScale:o,maskColorString:tl(t)}}),u_=e=>`data:image/svg+xml;utf8, + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +`.replaceAll("black",e),qle=e=>{const{...t}=e,{maskColorString:n,stageCoordinates:r,stageDimensions:o,stageScale:s}=z(Gle),[a,c]=f.useState(null),[d,p]=f.useState(0),h=f.useRef(null),m=f.useCallback(()=>{p(d+1),setTimeout(m,500)},[d]);return f.useEffect(()=>{if(a)return;const v=new Image;v.onload=()=>{c(v)},v.src=u_(n)},[a,n]),f.useEffect(()=>{a&&(a.src=u_(n))},[a,n]),f.useEffect(()=>{const v=setInterval(()=>p(b=>(b+1)%5),50);return()=>clearInterval(v)},[]),!a||!Ml(r.x)||!Ml(r.y)||!Ml(s)||!Ml(o.width)||!Ml(o.height)?null:i.jsx(aa,{ref:h,offsetX:r.x/s,offsetY:r.y/s,height:o.height/s,width:o.width/s,fillPatternImage:a,fillPatternOffsetY:Ml(d)?d:0,fillPatternRepeat:"repeat",fillPatternScale:{x:1/s,y:1/s},listening:!0,globalCompositeOperation:"source-in",...t})},Kle=fe([mn],e=>({objects:e.layerState.objects}),{memoizeOptions:{resultEqualityCheck:Qt}}),Yle=e=>{const{...t}=e,{objects:n}=z(Kle);return i.jsx(Na,{listening:!1,...t,children:n.filter(nD).map((r,o)=>i.jsx(Yh,{points:r.points,stroke:"rgb(0,0,0)",strokeWidth:r.strokeWidth*2,tension:0,lineCap:"round",lineJoin:"round",shadowForStrokeEnabled:!1,listening:!1,globalCompositeOperation:r.tool==="brush"?"source-over":"destination-out"},o))})};var Wi=f,Xle=function(t,n,r){const o=Wi.useRef("loading"),s=Wi.useRef(),[a,c]=Wi.useState(0),d=Wi.useRef(),p=Wi.useRef(),h=Wi.useRef();return(d.current!==t||p.current!==n||h.current!==r)&&(o.current="loading",s.current=void 0,d.current=t,p.current=n,h.current=r),Wi.useLayoutEffect(function(){if(!t)return;var m=document.createElement("img");function v(){o.current="loaded",s.current=m,c(Math.random())}function b(){o.current="failed",s.current=void 0,c(Math.random())}return m.addEventListener("load",v),m.addEventListener("error",b),n&&(m.crossOrigin=n),r&&(m.referrerPolicy=r),m.src=t,function(){m.removeEventListener("load",v),m.removeEventListener("error",b)}},[t,n,r]),[s.current,o.current]};const Qle=cd(Xle),d8=e=>{const{width:t,height:n,x:r,y:o,imageName:s}=e.canvasImage,{currentData:a,isError:c}=os(s??oo.skipToken),[d]=Qle((a==null?void 0:a.image_url)??"",rD.get()?"use-credentials":"anonymous");return c?i.jsx(aa,{x:r,y:o,width:t,height:n,fill:"red"}):i.jsx(c8,{x:r,y:o,image:d,listening:!1})},Jle=fe([mn],e=>{const{layerState:{objects:t}}=e;return{objects:t}},{memoizeOptions:{resultEqualityCheck:Qt}}),Zle=()=>{const{objects:e}=z(Jle);return e?i.jsx(Na,{name:"outpainting-objects",listening:!1,children:e.map((t,n)=>{if(I_(t))return i.jsx(d8,{canvasImage:t},n);if(oD(t)){const r=i.jsx(Yh,{points:t.points,stroke:t.color?tl(t.color):"rgb(0,0,0)",strokeWidth:t.strokeWidth*2,tension:0,lineCap:"round",lineJoin:"round",shadowForStrokeEnabled:!1,listening:!1,globalCompositeOperation:t.tool==="brush"?"source-over":"destination-out"},n);return t.clip?i.jsx(Na,{clipX:t.clip.x,clipY:t.clip.y,clipWidth:t.clip.width,clipHeight:t.clip.height,children:r},n):r}else{if(sD(t))return i.jsx(aa,{x:t.x,y:t.y,width:t.width,height:t.height,fill:tl(t.color)},n);if(aD(t))return i.jsx(aa,{x:t.x,y:t.y,width:t.width,height:t.height,fill:"rgb(255, 255, 255)",globalCompositeOperation:"destination-out"},n)}})}):null},ece=fe([mn],e=>{const{layerState:t,shouldShowStagingImage:n,shouldShowStagingOutline:r,boundingBoxCoordinates:{x:o,y:s},boundingBoxDimensions:{width:a,height:c}}=e,{selectedImageIndex:d,images:p}=t.stagingArea;return{currentStagingAreaImage:p.length>0&&d!==void 0?p[d]:void 0,isOnFirstImage:d===0,isOnLastImage:d===p.length-1,shouldShowStagingImage:n,shouldShowStagingOutline:r,x:o,y:s,width:a,height:c}},{memoizeOptions:{resultEqualityCheck:Qt}}),tce=e=>{const{...t}=e,{currentStagingAreaImage:n,shouldShowStagingImage:r,shouldShowStagingOutline:o,x:s,y:a,width:c,height:d}=z(ece);return i.jsxs(Na,{...t,children:[r&&n&&i.jsx(d8,{canvasImage:n}),o&&i.jsxs(Na,{children:[i.jsx(aa,{x:s,y:a,width:c,height:d,strokeWidth:1,stroke:"white",strokeScaleEnabled:!1}),i.jsx(aa,{x:s,y:a,width:c,height:d,dash:[4,4],strokeWidth:1,stroke:"black",strokeScaleEnabled:!1})]})]})},nce=fe([mn],e=>{const{layerState:{stagingArea:{images:t,selectedImageIndex:n,sessionId:r}},shouldShowStagingOutline:o,shouldShowStagingImage:s}=e;return{currentStagingAreaImage:t.length>0?t[n]:void 0,isOnFirstImage:n===0,isOnLastImage:n===t.length-1,shouldShowStagingImage:s,shouldShowStagingOutline:o,sessionId:r}},{memoizeOptions:{resultEqualityCheck:Qt}}),rce=()=>{const e=te(),{isOnFirstImage:t,isOnLastImage:n,currentStagingAreaImage:r,shouldShowStagingImage:o,sessionId:s}=z(nce),{t:a}=be(),c=f.useCallback(()=>{e(iw(!0))},[e]),d=f.useCallback(()=>{e(iw(!1))},[e]);nt(["left"],()=>{p()},{enabled:()=>!0,preventDefault:!0}),nt(["right"],()=>{h()},{enabled:()=>!0,preventDefault:!0}),nt(["enter"],()=>{m()},{enabled:()=>!0,preventDefault:!0});const p=f.useCallback(()=>e(iD()),[e]),h=f.useCallback(()=>e(lD()),[e]),m=f.useCallback(()=>e(cD(s)),[e,s]),{data:v}=os((r==null?void 0:r.imageName)??oo.skipToken);return r?i.jsx(H,{pos:"absolute",bottom:4,w:"100%",align:"center",justify:"center",filter:"drop-shadow(0 0.5rem 1rem rgba(0,0,0))",onMouseOver:c,onMouseOut:d,children:i.jsxs(nr,{isAttached:!0,children:[i.jsx(Le,{tooltip:`${a("unifiedCanvas.previous")} (Left)`,"aria-label":`${a("unifiedCanvas.previous")} (Left)`,icon:i.jsx(LH,{}),onClick:p,colorScheme:"accent",isDisabled:t}),i.jsx(Le,{tooltip:`${a("unifiedCanvas.next")} (Right)`,"aria-label":`${a("unifiedCanvas.next")} (Right)`,icon:i.jsx(BH,{}),onClick:h,colorScheme:"accent",isDisabled:n}),i.jsx(Le,{tooltip:`${a("unifiedCanvas.accept")} (Enter)`,"aria-label":`${a("unifiedCanvas.accept")} (Enter)`,icon:i.jsx(WH,{}),onClick:m,colorScheme:"accent"}),i.jsx(Le,{tooltip:a("unifiedCanvas.showHide"),"aria-label":a("unifiedCanvas.showHide"),"data-alert":!o,icon:o?i.jsx(JH,{}):i.jsx(QH,{}),onClick:()=>e(uD(!o)),colorScheme:"accent"}),i.jsx(Le,{tooltip:a("unifiedCanvas.saveToGallery"),"aria-label":a("unifiedCanvas.saveToGallery"),isDisabled:!v||!v.is_intermediate,icon:i.jsx(_m,{}),onClick:()=>{v&&e(dD({imageDTO:v}))},colorScheme:"accent"}),i.jsx(Le,{tooltip:a("unifiedCanvas.discardAll"),"aria-label":a("unifiedCanvas.discardAll"),icon:i.jsx(ml,{style:{transform:"rotate(45deg)"}}),onClick:()=>e(fD()),colorScheme:"error",fontSize:20})]})}):null},oce=()=>{const e=z(c=>c.canvas.layerState),t=z(c=>c.canvas.boundingBoxCoordinates),n=z(c=>c.canvas.boundingBoxDimensions),r=z(c=>c.canvas.isMaskEnabled),o=z(c=>c.canvas.shouldPreserveMaskedArea),[s,a]=f.useState();return f.useEffect(()=>{a(void 0)},[e,t,n,r,o]),oee(async()=>{const c=await pD(e,t,n,r,o);if(!c)return;const{baseImageData:d,maskImageData:p}=c,h=hD(d,p);a(h)},1e3,[e,t,n,r,o]),s},sce={txt2img:"Text to Image",img2img:"Image to Image",inpaint:"Inpaint",outpaint:"Inpaint"},ace=()=>{const e=oce();return i.jsxs(Oe,{children:["Mode: ",e?sce[e]:"..."]})},Jl=e=>Math.round(e*100)/100,ice=fe([mn],e=>{const{cursorPosition:t}=e,{cursorX:n,cursorY:r}=t?{cursorX:t.x,cursorY:t.y}:{cursorX:-1,cursorY:-1};return{cursorCoordinatesString:`(${Jl(n)}, ${Jl(r)})`}},{memoizeOptions:{resultEqualityCheck:Qt}});function lce(){const{cursorCoordinatesString:e}=z(ice),{t}=be();return i.jsx(Oe,{children:`${t("unifiedCanvas.cursorPosition")}: ${e}`})}const R1="var(--invokeai-colors-warning-500)",cce=fe([mn],e=>{const{stageDimensions:{width:t,height:n},stageCoordinates:{x:r,y:o},boundingBoxDimensions:{width:s,height:a},scaledBoundingBoxDimensions:{width:c,height:d},boundingBoxCoordinates:{x:p,y:h},stageScale:m,shouldShowCanvasDebugInfo:v,layer:b,boundingBoxScaleMethod:w,shouldPreserveMaskedArea:y}=e;let S="inherit";return(w==="none"&&(s<512||a<512)||w==="manual"&&c*d<512*512)&&(S=R1),{activeLayerColor:b==="mask"?R1:"inherit",activeLayerString:b.charAt(0).toUpperCase()+b.slice(1),boundingBoxColor:S,boundingBoxCoordinatesString:`(${Jl(p)}, ${Jl(h)})`,boundingBoxDimensionsString:`${s}×${a}`,scaledBoundingBoxDimensionsString:`${c}×${d}`,canvasCoordinatesString:`${Jl(r)}×${Jl(o)}`,canvasDimensionsString:`${t}×${n}`,canvasScaleString:Math.round(m*100),shouldShowCanvasDebugInfo:v,shouldShowBoundingBox:w!=="auto",shouldShowScaledBoundingBox:w!=="none",shouldPreserveMaskedArea:y}},{memoizeOptions:{resultEqualityCheck:Qt}}),uce=()=>{const{activeLayerColor:e,activeLayerString:t,boundingBoxColor:n,boundingBoxCoordinatesString:r,boundingBoxDimensionsString:o,scaledBoundingBoxDimensionsString:s,shouldShowScaledBoundingBox:a,canvasCoordinatesString:c,canvasDimensionsString:d,canvasScaleString:p,shouldShowCanvasDebugInfo:h,shouldShowBoundingBox:m,shouldPreserveMaskedArea:v}=z(cce),{t:b}=be();return i.jsxs(H,{sx:{flexDirection:"column",position:"absolute",top:0,insetInlineStart:0,opacity:.65,display:"flex",fontSize:"sm",padding:1,px:2,minWidth:48,margin:1,borderRadius:"base",pointerEvents:"none",bg:"base.200",_dark:{bg:"base.800"}},children:[i.jsx(ace,{}),i.jsx(Oe,{style:{color:e},children:`${b("unifiedCanvas.activeLayer")}: ${t}`}),i.jsx(Oe,{children:`${b("unifiedCanvas.canvasScale")}: ${p}%`}),v&&i.jsx(Oe,{style:{color:R1},children:"Preserve Masked Area: On"}),m&&i.jsx(Oe,{style:{color:n},children:`${b("unifiedCanvas.boundingBox")}: ${o}`}),a&&i.jsx(Oe,{style:{color:n},children:`${b("unifiedCanvas.scaledBoundingBox")}: ${s}`}),h&&i.jsxs(i.Fragment,{children:[i.jsx(Oe,{children:`${b("unifiedCanvas.boundingBoxPosition")}: ${r}`}),i.jsx(Oe,{children:`${b("unifiedCanvas.canvasDimensions")}: ${d}`}),i.jsx(Oe,{children:`${b("unifiedCanvas.canvasPosition")}: ${c}`}),i.jsx(lce,{})]})]})},dce=fe([Ye],({canvas:e,generation:t})=>{const{boundingBoxCoordinates:n,boundingBoxDimensions:r,stageScale:o,isDrawing:s,isTransformingBoundingBox:a,isMovingBoundingBox:c,tool:d,shouldSnapToGrid:p}=e,{aspectRatio:h}=t;return{boundingBoxCoordinates:n,boundingBoxDimensions:r,isDrawing:s,isMovingBoundingBox:c,isTransformingBoundingBox:a,stageScale:o,shouldSnapToGrid:p,tool:d,hitStrokeWidth:20/o,aspectRatio:h}},{memoizeOptions:{resultEqualityCheck:Qt}}),fce=e=>{const{...t}=e,n=te(),{boundingBoxCoordinates:r,boundingBoxDimensions:o,isDrawing:s,isMovingBoundingBox:a,isTransformingBoundingBox:c,stageScale:d,shouldSnapToGrid:p,tool:h,hitStrokeWidth:m,aspectRatio:v}=z(dce),b=f.useRef(null),w=f.useRef(null),[y,S]=f.useState(!1);f.useEffect(()=>{var B;!b.current||!w.current||(b.current.nodes([w.current]),(B=b.current.getLayer())==null||B.batchDraw())},[]);const k=64*d;nt("N",()=>{n(Wu(!p))});const _=f.useCallback(B=>{if(!p){n(a0({x:Math.floor(B.target.x()),y:Math.floor(B.target.y())}));return}const V=B.target.x(),q=B.target.y(),G=Ss(V,64),D=Ss(q,64);B.target.x(G),B.target.y(D),n(a0({x:G,y:D}))},[n,p]),I=f.useCallback(()=>{if(!w.current)return;const B=w.current,V=B.scaleX(),q=B.scaleY(),G=Math.round(B.width()*V),D=Math.round(B.height()*q),L=Math.round(B.x()),W=Math.round(B.y());if(v){const Y=Ss(G/v,64);n(Js({width:G,height:Y}))}else n(Js({width:G,height:D}));n(a0({x:p?wu(L,64):L,y:p?wu(W,64):W})),B.scaleX(1),B.scaleY(1)},[n,p,v]),P=f.useCallback((B,V,q)=>{const G=B.x%k,D=B.y%k;return{x:wu(V.x,k)+G,y:wu(V.y,k)+D}},[k]),E=()=>{n(i0(!0))},O=()=>{n(i0(!1)),n(l0(!1)),n(Rf(!1)),S(!1)},R=()=>{n(l0(!0))},M=()=>{n(i0(!1)),n(l0(!1)),n(Rf(!1)),S(!1)},T=()=>{S(!0)},A=()=>{!c&&!a&&S(!1)},$=()=>{n(Rf(!0))},Q=()=>{n(Rf(!1))};return i.jsxs(Na,{...t,children:[i.jsx(aa,{height:o.height,width:o.width,x:r.x,y:r.y,onMouseEnter:$,onMouseOver:$,onMouseLeave:Q,onMouseOut:Q}),i.jsx(aa,{draggable:!0,fillEnabled:!1,height:o.height,hitStrokeWidth:m,listening:!s&&h==="move",onDragStart:R,onDragEnd:M,onDragMove:_,onMouseDown:R,onMouseOut:A,onMouseOver:T,onMouseEnter:T,onMouseUp:M,onTransform:I,onTransformEnd:O,ref:w,stroke:y?"rgba(255,255,255,0.7)":"white",strokeWidth:(y?8:1)/d,width:o.width,x:r.x,y:r.y}),i.jsx(_le,{anchorCornerRadius:3,anchorDragBoundFunc:P,anchorFill:"rgba(212,216,234,1)",anchorSize:15,anchorStroke:"rgb(42,42,42)",borderDash:[4,4],borderEnabled:!0,borderStroke:"black",draggable:!1,enabledAnchors:h==="move"?void 0:[],flipEnabled:!1,ignoreStroke:!0,keepRatio:!1,listening:!s&&h==="move",onDragStart:R,onDragEnd:M,onMouseDown:E,onMouseUp:O,onTransformEnd:O,ref:b,rotateEnabled:!1})]})},pce=fe(mn,e=>{const{cursorPosition:t,brushSize:n,colorPickerColor:r,maskColor:o,brushColor:s,tool:a,layer:c,shouldShowBrush:d,isMovingBoundingBox:p,isTransformingBoundingBox:h,stageScale:m,stageDimensions:v,boundingBoxCoordinates:b,boundingBoxDimensions:w,shouldRestrictStrokesToBox:y}=e,S=y?{clipX:b.x,clipY:b.y,clipWidth:w.width,clipHeight:w.height}:{};return{cursorPosition:t,brushX:t?t.x:v.width/2,brushY:t?t.y:v.height/2,radius:n/2,colorPickerOuterRadius:lw/m,colorPickerInnerRadius:(lw-bv+1)/m,maskColorString:tl({...o,a:.5}),brushColorString:tl(s),colorPickerColorString:tl(r),tool:a,layer:c,shouldShowBrush:d,shouldDrawBrushPreview:!(p||h||!t)&&d,strokeWidth:1.5/m,dotRadius:1.5/m,clip:S}},{memoizeOptions:{resultEqualityCheck:Qt}}),hce=e=>{const{...t}=e,{brushX:n,brushY:r,radius:o,maskColorString:s,tool:a,layer:c,shouldDrawBrushPreview:d,dotRadius:p,strokeWidth:h,brushColorString:m,colorPickerColorString:v,colorPickerInnerRadius:b,colorPickerOuterRadius:w,clip:y}=z(pce);return d?i.jsxs(Na,{listening:!1,...y,...t,children:[a==="colorPicker"?i.jsxs(i.Fragment,{children:[i.jsx(Hi,{x:n,y:r,radius:w,stroke:m,strokeWidth:bv,strokeScaleEnabled:!1}),i.jsx(Hi,{x:n,y:r,radius:b,stroke:v,strokeWidth:bv,strokeScaleEnabled:!1})]}):i.jsxs(i.Fragment,{children:[i.jsx(Hi,{x:n,y:r,radius:o,fill:c==="mask"?s:m,globalCompositeOperation:a==="eraser"?"destination-out":"source-out"}),i.jsx(Hi,{x:n,y:r,radius:o,stroke:"rgba(255,255,255,0.4)",strokeWidth:h*2,strokeEnabled:!0,listening:!1}),i.jsx(Hi,{x:n,y:r,radius:o,stroke:"rgba(0,0,0,1)",strokeWidth:h,strokeEnabled:!0,listening:!1})]}),i.jsx(Hi,{x:n,y:r,radius:p*2,fill:"rgba(255,255,255,0.4)",listening:!1}),i.jsx(Hi,{x:n,y:r,radius:p,fill:"rgba(0,0,0,1)",listening:!1})]}):null},mce=fe([mn,ir],(e,t)=>{const{isMaskEnabled:n,stageScale:r,shouldShowBoundingBox:o,isTransformingBoundingBox:s,isMouseOverBoundingBox:a,isMovingBoundingBox:c,stageDimensions:d,stageCoordinates:p,tool:h,isMovingStage:m,shouldShowIntermediates:v,shouldShowGrid:b,shouldRestrictStrokesToBox:w,shouldAntialias:y}=e;let S="none";return h==="move"||t?m?S="grabbing":S="grab":s?S=void 0:w&&!a&&(S="default"),{isMaskEnabled:n,isModifyingBoundingBox:s||c,shouldShowBoundingBox:o,shouldShowGrid:b,stageCoordinates:p,stageCursor:S,stageDimensions:d,stageScale:r,tool:h,isStaging:t,shouldShowIntermediates:v,shouldAntialias:y}},Ge),gce=Ie(Ple,{shouldForwardProp:e=>!["sx"].includes(e)}),d_=()=>{const{isMaskEnabled:e,isModifyingBoundingBox:t,shouldShowBoundingBox:n,shouldShowGrid:r,stageCoordinates:o,stageCursor:s,stageDimensions:a,stageScale:c,tool:d,isStaging:p,shouldShowIntermediates:h,shouldAntialias:m}=z(mce);Ole();const v=f.useRef(null),b=f.useRef(null),w=f.useCallback(A=>{gD(A),v.current=A},[]),y=f.useCallback(A=>{mD(A),b.current=A},[]),S=f.useRef({x:0,y:0}),k=f.useRef(!1),_=Lle(v),I=Mle(v),P=$le(v,k),E=Tle(v,k,S),O=Ale(),{handleDragStart:R,handleDragMove:M,handleDragEnd:T}=Ile();return i.jsx(H,{sx:{position:"relative",height:"100%",width:"100%",borderRadius:"base"},children:i.jsxs(Oe,{sx:{position:"relative"},children:[i.jsxs(gce,{tabIndex:-1,ref:w,sx:{outline:"none",overflow:"hidden",cursor:s||void 0,canvas:{outline:"none"}},x:o.x,y:o.y,width:a.width,height:a.height,scale:{x:c,y:c},onTouchStart:I,onTouchMove:E,onTouchEnd:P,onMouseDown:I,onMouseLeave:O,onMouseMove:E,onMouseUp:P,onDragStart:R,onDragMove:M,onDragEnd:T,onContextMenu:A=>A.evt.preventDefault(),onWheel:_,draggable:(d==="move"||p)&&!t,children:[i.jsx(yu,{id:"grid",visible:r,children:i.jsx(Wle,{})}),i.jsx(yu,{id:"base",ref:y,listening:!1,imageSmoothingEnabled:m,children:i.jsx(Zle,{})}),i.jsxs(yu,{id:"mask",visible:e,listening:!1,children:[i.jsx(Yle,{visible:!0,listening:!1}),i.jsx(qle,{listening:!1})]}),i.jsx(yu,{children:i.jsx(Fle,{})}),i.jsxs(yu,{id:"preview",imageSmoothingEnabled:m,children:[!p&&i.jsx(hce,{visible:d!=="move",listening:!1}),i.jsx(tce,{visible:p}),h&&i.jsx(Ule,{}),i.jsx(fce,{visible:n&&!p})]})]}),i.jsx(uce,{}),i.jsx(rce,{})]})})},vce=fe(mn,hH,Kn,(e,t,n)=>{const{doesCanvasNeedScaling:r,isCanvasInitialized:o}=e;return{doesCanvasNeedScaling:r,activeTabName:n,initialCanvasImage:t,isCanvasInitialized:o}}),f_=()=>{const e=te(),{doesCanvasNeedScaling:t,activeTabName:n,initialCanvasImage:r,isCanvasInitialized:o}=z(vce),s=f.useRef(null);return f.useLayoutEffect(()=>{window.setTimeout(()=>{if(!s.current)return;const{clientWidth:a,clientHeight:c}=s.current;e(vD({width:a,height:c})),e(o?bD():em()),e(E_(!1))},0)},[e,r,t,n,o]),i.jsx(H,{ref:s,sx:{flexDirection:"column",alignItems:"center",justifyContent:"center",gap:4,width:"100%",height:"100%"},children:i.jsx(dl,{thickness:"2px",size:"xl"})})};function f8(e,t,n=250){const[r,o]=f.useState(0);return f.useEffect(()=>{const s=setTimeout(()=>{r===1&&e(),o(0)},n);return r===2&&t(),()=>clearTimeout(s)},[r,e,t,n]),()=>o(s=>s+1)}const bce=Ie(YO,{baseStyle:{paddingInline:4},shouldForwardProp:e=>!["pickerColor"].includes(e)}),sv={width:6,height:6,borderColor:"base.100"},yce=e=>{const{styleClass:t="",...n}=e;return i.jsx(bce,{sx:{".react-colorful__hue-pointer":sv,".react-colorful__saturation-pointer":sv,".react-colorful__alpha-pointer":sv},className:t,...n})},Xh=f.memo(yce),xce=fe([mn,ir],(e,t)=>{const{maskColor:n,layer:r,isMaskEnabled:o,shouldPreserveMaskedArea:s}=e;return{layer:r,maskColor:n,maskColorString:tl(n),isMaskEnabled:o,shouldPreserveMaskedArea:s,isStaging:t}},{memoizeOptions:{resultEqualityCheck:Qt}}),wce=()=>{const e=te(),{t}=be(),{layer:n,maskColor:r,isMaskEnabled:o,shouldPreserveMaskedArea:s,isStaging:a}=z(xce);nt(["q"],()=>{c()},{enabled:()=>!a,preventDefault:!0},[n]),nt(["shift+c"],()=>{d()},{enabled:()=>!a,preventDefault:!0},[]),nt(["h"],()=>{p()},{enabled:()=>!a,preventDefault:!0},[o]);const c=()=>{e(Np(n==="mask"?"base":"mask"))},d=()=>e(q1()),p=()=>e(pd(!o));return i.jsx(gl,{triggerComponent:i.jsx(nr,{children:i.jsx(Le,{"aria-label":t("unifiedCanvas.maskingOptions"),tooltip:t("unifiedCanvas.maskingOptions"),icon:i.jsx(iW,{}),isChecked:n==="mask",isDisabled:a})}),children:i.jsxs(H,{direction:"column",gap:2,children:[i.jsx(Gn,{label:`${t("unifiedCanvas.enableMask")} (H)`,isChecked:o,onChange:p}),i.jsx(Gn,{label:t("unifiedCanvas.preserveMaskedArea"),isChecked:s,onChange:h=>e(a3(h.target.checked))}),i.jsx(Xh,{sx:{paddingTop:2,paddingBottom:2},pickerColor:r,onChange:h=>e(i3(h))}),i.jsxs(rn,{size:"sm",leftIcon:i.jsx(us,{}),onClick:d,children:[t("unifiedCanvas.clearMask")," (Shift+C)"]})]})})},Sce=fe([mn,Kn,mo],(e,t,n)=>{const{futureLayerStates:r}=e;return{canRedo:r.length>0&&!n.isProcessing,activeTabName:t}},{memoizeOptions:{resultEqualityCheck:Qt}});function p8(){const e=te(),{canRedo:t,activeTabName:n}=z(Sce),{t:r}=be(),o=()=>{e(yD())};return nt(["meta+shift+z","ctrl+shift+z","control+y","meta+y"],()=>{o()},{enabled:()=>t,preventDefault:!0},[n,t]),i.jsx(Le,{"aria-label":`${r("unifiedCanvas.redo")} (Ctrl+Shift+Z)`,tooltip:`${r("unifiedCanvas.redo")} (Ctrl+Shift+Z)`,icon:i.jsx(uW,{}),onClick:o,isDisabled:!t})}const h8=()=>{const e=z(ir),t=te(),{t:n}=be();return i.jsxs(Vy,{title:n("unifiedCanvas.clearCanvasHistory"),acceptCallback:()=>t(xD()),acceptButtonText:n("unifiedCanvas.clearHistory"),triggerComponent:i.jsx(rn,{size:"sm",leftIcon:i.jsx(us,{}),isDisabled:e,children:n("unifiedCanvas.clearCanvasHistory")}),children:[i.jsx("p",{children:n("unifiedCanvas.clearCanvasHistoryMessage")}),i.jsx("br",{}),i.jsx("p",{children:n("unifiedCanvas.clearCanvasHistoryConfirm")})]})},Cce=fe([mn],e=>{const{shouldAutoSave:t,shouldCropToBoundingBoxOnSave:n,shouldDarkenOutsideBoundingBox:r,shouldShowCanvasDebugInfo:o,shouldShowGrid:s,shouldShowIntermediates:a,shouldSnapToGrid:c,shouldRestrictStrokesToBox:d,shouldAntialias:p}=e;return{shouldAutoSave:t,shouldCropToBoundingBoxOnSave:n,shouldDarkenOutsideBoundingBox:r,shouldShowCanvasDebugInfo:o,shouldShowGrid:s,shouldShowIntermediates:a,shouldSnapToGrid:c,shouldRestrictStrokesToBox:d,shouldAntialias:p}},{memoizeOptions:{resultEqualityCheck:Qt}}),kce=()=>{const e=te(),{t}=be(),{shouldAutoSave:n,shouldCropToBoundingBoxOnSave:r,shouldDarkenOutsideBoundingBox:o,shouldShowCanvasDebugInfo:s,shouldShowGrid:a,shouldShowIntermediates:c,shouldSnapToGrid:d,shouldRestrictStrokesToBox:p,shouldAntialias:h}=z(Cce);nt(["n"],()=>{e(Wu(!d))},{enabled:!0,preventDefault:!0},[d]);const m=v=>e(Wu(v.target.checked));return i.jsx(gl,{isLazy:!1,triggerComponent:i.jsx(Le,{tooltip:t("unifiedCanvas.canvasSettings"),"aria-label":t("unifiedCanvas.canvasSettings"),icon:i.jsx(Wb,{})}),children:i.jsxs(H,{direction:"column",gap:2,children:[i.jsx(Gn,{label:t("unifiedCanvas.showIntermediates"),isChecked:c,onChange:v=>e(l3(v.target.checked))}),i.jsx(Gn,{label:t("unifiedCanvas.showGrid"),isChecked:a,onChange:v=>e(c3(v.target.checked))}),i.jsx(Gn,{label:t("unifiedCanvas.snapToGrid"),isChecked:d,onChange:m}),i.jsx(Gn,{label:t("unifiedCanvas.darkenOutsideSelection"),isChecked:o,onChange:v=>e(u3(v.target.checked))}),i.jsx(Gn,{label:t("unifiedCanvas.autoSaveToGallery"),isChecked:n,onChange:v=>e(d3(v.target.checked))}),i.jsx(Gn,{label:t("unifiedCanvas.saveBoxRegionOnly"),isChecked:r,onChange:v=>e(f3(v.target.checked))}),i.jsx(Gn,{label:t("unifiedCanvas.limitStrokesToBox"),isChecked:p,onChange:v=>e(p3(v.target.checked))}),i.jsx(Gn,{label:t("unifiedCanvas.showCanvasDebugInfo"),isChecked:s,onChange:v=>e(h3(v.target.checked))}),i.jsx(Gn,{label:t("unifiedCanvas.antialiasing"),isChecked:h,onChange:v=>e(m3(v.target.checked))}),i.jsx(h8,{})]})})},_ce=fe([mn,ir,mo],(e,t,n)=>{const{isProcessing:r}=n,{tool:o,brushColor:s,brushSize:a}=e;return{tool:o,isStaging:t,isProcessing:r,brushColor:s,brushSize:a}},{memoizeOptions:{resultEqualityCheck:Qt}}),Pce=()=>{const e=te(),{tool:t,brushColor:n,brushSize:r,isStaging:o}=z(_ce),{t:s}=be();nt(["b"],()=>{a()},{enabled:()=>!o,preventDefault:!0},[]),nt(["e"],()=>{c()},{enabled:()=>!o,preventDefault:!0},[t]),nt(["c"],()=>{d()},{enabled:()=>!o,preventDefault:!0},[t]),nt(["shift+f"],()=>{p()},{enabled:()=>!o,preventDefault:!0}),nt(["delete","backspace"],()=>{h()},{enabled:()=>!o,preventDefault:!0}),nt(["BracketLeft"],()=>{e(ec(Math.max(r-5,5)))},{enabled:()=>!o,preventDefault:!0},[r]),nt(["BracketRight"],()=>{e(ec(Math.min(r+5,500)))},{enabled:()=>!o,preventDefault:!0},[r]),nt(["Shift+BracketLeft"],()=>{e(tc({...n,a:Es(n.a-.05,.05,1)}))},{enabled:()=>!o,preventDefault:!0},[n]),nt(["Shift+BracketRight"],()=>{e(tc({...n,a:Es(n.a+.05,.05,1)}))},{enabled:()=>!o,preventDefault:!0},[n]);const a=()=>e(ea("brush")),c=()=>e(ea("eraser")),d=()=>e(ea("colorPicker")),p=()=>e(g3()),h=()=>e(v3());return i.jsxs(nr,{isAttached:!0,children:[i.jsx(Le,{"aria-label":`${s("unifiedCanvas.brush")} (B)`,tooltip:`${s("unifiedCanvas.brush")} (B)`,icon:i.jsx(b6,{}),isChecked:t==="brush"&&!o,onClick:a,isDisabled:o}),i.jsx(Le,{"aria-label":`${s("unifiedCanvas.eraser")} (E)`,tooltip:`${s("unifiedCanvas.eraser")} (E)`,icon:i.jsx(p6,{}),isChecked:t==="eraser"&&!o,isDisabled:o,onClick:c}),i.jsx(Le,{"aria-label":`${s("unifiedCanvas.fillBoundingBox")} (Shift+F)`,tooltip:`${s("unifiedCanvas.fillBoundingBox")} (Shift+F)`,icon:i.jsx(g6,{}),isDisabled:o,onClick:p}),i.jsx(Le,{"aria-label":`${s("unifiedCanvas.eraseBoundingBox")} (Del/Backspace)`,tooltip:`${s("unifiedCanvas.eraseBoundingBox")} (Del/Backspace)`,icon:i.jsx(ml,{style:{transform:"rotate(45deg)"}}),isDisabled:o,onClick:h}),i.jsx(Le,{"aria-label":`${s("unifiedCanvas.colorPicker")} (C)`,tooltip:`${s("unifiedCanvas.colorPicker")} (C)`,icon:i.jsx(m6,{}),isChecked:t==="colorPicker"&&!o,isDisabled:o,onClick:d}),i.jsx(gl,{triggerComponent:i.jsx(Le,{"aria-label":s("unifiedCanvas.brushOptions"),tooltip:s("unifiedCanvas.brushOptions"),icon:i.jsx(Fb,{})}),children:i.jsxs(H,{minWidth:60,direction:"column",gap:4,width:"100%",children:[i.jsx(H,{gap:4,justifyContent:"space-between",children:i.jsx(_t,{label:s("unifiedCanvas.brushSize"),value:r,withInput:!0,onChange:m=>e(ec(m)),sliderNumberInputProps:{max:500}})}),i.jsx(Xh,{sx:{width:"100%",paddingTop:2,paddingBottom:2},pickerColor:n,onChange:m=>e(tc(m))})]})})]})},jce=fe([mn,Kn,mo],(e,t,n)=>{const{pastLayerStates:r}=e;return{canUndo:r.length>0&&!n.isProcessing,activeTabName:t}},{memoizeOptions:{resultEqualityCheck:Qt}});function m8(){const e=te(),{t}=be(),{canUndo:n,activeTabName:r}=z(jce),o=()=>{e(wD())};return nt(["meta+z","ctrl+z"],()=>{o()},{enabled:()=>n,preventDefault:!0},[r,n]),i.jsx(Le,{"aria-label":`${t("unifiedCanvas.undo")} (Ctrl+Z)`,tooltip:`${t("unifiedCanvas.undo")} (Ctrl+Z)`,icon:i.jsx(Hb,{}),onClick:o,isDisabled:!n})}const Ice=fe([mo,mn,ir],(e,t,n)=>{const{isProcessing:r}=e,{tool:o,shouldCropToBoundingBoxOnSave:s,layer:a,isMaskEnabled:c}=t;return{isProcessing:r,isStaging:n,isMaskEnabled:c,tool:o,layer:a,shouldCropToBoundingBoxOnSave:s}},{memoizeOptions:{resultEqualityCheck:Qt}}),Ece=()=>{const e=te(),{isProcessing:t,isStaging:n,isMaskEnabled:r,layer:o,tool:s}=z(Ice),a=Ia(),{t:c}=be(),{isClipboardAPIAvailable:d}=Oy(),{getUploadButtonProps:p,getUploadInputProps:h}=Vm({postUploadAction:{type:"SET_CANVAS_INITIAL_IMAGE"}});nt(["v"],()=>{m()},{enabled:()=>!n,preventDefault:!0},[]),nt(["r"],()=>{b()},{enabled:()=>!0,preventDefault:!0},[a]),nt(["shift+m"],()=>{y()},{enabled:()=>!n,preventDefault:!0},[a,t]),nt(["shift+s"],()=>{S()},{enabled:()=>!n,preventDefault:!0},[a,t]),nt(["meta+c","ctrl+c"],()=>{k()},{enabled:()=>!n&&d,preventDefault:!0},[a,t,d]),nt(["shift+d"],()=>{_()},{enabled:()=>!n,preventDefault:!0},[a,t]);const m=()=>e(ea("move")),v=f8(()=>b(!1),()=>b(!0)),b=(P=!1)=>{const E=Ia();if(!E)return;const O=E.getClientRect({skipTransform:!0});e(b3({contentRect:O,shouldScaleTo1:P}))},w=()=>{e(F1()),e(em())},y=()=>{e(y3())},S=()=>{e(x3())},k=()=>{d&&e(w3())},_=()=>{e(S3())},I=P=>{const E=P;e(Np(E)),E==="mask"&&!r&&e(pd(!0))};return i.jsxs(H,{sx:{alignItems:"center",gap:2,flexWrap:"wrap"},children:[i.jsx(Oe,{w:24,children:i.jsx(Yr,{tooltip:`${c("unifiedCanvas.layer")} (Q)`,value:o,data:C3,onChange:I,disabled:n})}),i.jsx(wce,{}),i.jsx(Pce,{}),i.jsxs(nr,{isAttached:!0,children:[i.jsx(Le,{"aria-label":`${c("unifiedCanvas.move")} (V)`,tooltip:`${c("unifiedCanvas.move")} (V)`,icon:i.jsx(u6,{}),isChecked:s==="move"||n,onClick:m}),i.jsx(Le,{"aria-label":`${c("unifiedCanvas.resetView")} (R)`,tooltip:`${c("unifiedCanvas.resetView")} (R)`,icon:i.jsx(f6,{}),onClick:v})]}),i.jsxs(nr,{isAttached:!0,children:[i.jsx(Le,{"aria-label":`${c("unifiedCanvas.mergeVisible")} (Shift+M)`,tooltip:`${c("unifiedCanvas.mergeVisible")} (Shift+M)`,icon:i.jsx(v6,{}),onClick:y,isDisabled:n}),i.jsx(Le,{"aria-label":`${c("unifiedCanvas.saveToGallery")} (Shift+S)`,tooltip:`${c("unifiedCanvas.saveToGallery")} (Shift+S)`,icon:i.jsx(_m,{}),onClick:S,isDisabled:n}),d&&i.jsx(Le,{"aria-label":`${c("unifiedCanvas.copyToClipboard")} (Cmd/Ctrl+C)`,tooltip:`${c("unifiedCanvas.copyToClipboard")} (Cmd/Ctrl+C)`,icon:i.jsx(Fc,{}),onClick:k,isDisabled:n}),i.jsx(Le,{"aria-label":`${c("unifiedCanvas.downloadAsImage")} (Shift+D)`,tooltip:`${c("unifiedCanvas.downloadAsImage")} (Shift+D)`,icon:i.jsx(Bb,{}),onClick:_,isDisabled:n})]}),i.jsxs(nr,{isAttached:!0,children:[i.jsx(m8,{}),i.jsx(p8,{})]}),i.jsxs(nr,{isAttached:!0,children:[i.jsx(Le,{"aria-label":`${c("common.upload")}`,tooltip:`${c("common.upload")}`,icon:i.jsx(Md,{}),isDisabled:n,...p()}),i.jsx("input",{...h()}),i.jsx(Le,{"aria-label":`${c("unifiedCanvas.clearCanvas")}`,tooltip:`${c("unifiedCanvas.clearCanvas")}`,icon:i.jsx(us,{}),onClick:w,colorScheme:"error",isDisabled:n})]}),i.jsx(nr,{isAttached:!0,children:i.jsx(kce,{})})]})};function Oce(){const e=te(),t=z(o=>o.canvas.brushSize),{t:n}=be(),r=z(ir);return nt(["BracketLeft"],()=>{e(ec(Math.max(t-5,5)))},{enabled:()=>!r,preventDefault:!0},[t]),nt(["BracketRight"],()=>{e(ec(Math.min(t+5,500)))},{enabled:()=>!r,preventDefault:!0},[t]),i.jsx(_t,{label:n("unifiedCanvas.brushSize"),value:t,withInput:!0,onChange:o=>e(ec(o)),sliderNumberInputProps:{max:500},isCompact:!0})}const Rce=fe([mn,ir],(e,t)=>{const{brushColor:n,maskColor:r,layer:o}=e;return{brushColor:n,maskColor:r,layer:o,isStaging:t}},{memoizeOptions:{resultEqualityCheck:Qt}});function Mce(){const e=te(),{brushColor:t,maskColor:n,layer:r,isStaging:o}=z(Rce),s=()=>{if(r==="base")return`rgba(${t.r},${t.g},${t.b},${t.a})`;if(r==="mask")return`rgba(${n.r},${n.g},${n.b},${n.a})`};return nt(["shift+BracketLeft"],()=>{e(tc({...t,a:Es(t.a-.05,.05,1)}))},{enabled:()=>!o,preventDefault:!0},[t]),nt(["shift+BracketRight"],()=>{e(tc({...t,a:Es(t.a+.05,.05,1)}))},{enabled:()=>!o,preventDefault:!0},[t]),i.jsx(gl,{triggerComponent:i.jsx(Oe,{sx:{width:7,height:7,minWidth:7,minHeight:7,borderRadius:"full",bg:s(),cursor:"pointer"}}),children:i.jsxs(H,{minWidth:60,direction:"column",gap:4,width:"100%",children:[r==="base"&&i.jsx(Xh,{sx:{width:"100%",paddingTop:2,paddingBottom:2},pickerColor:t,onChange:a=>e(tc(a))}),r==="mask"&&i.jsx(Xh,{sx:{width:"100%",paddingTop:2,paddingBottom:2},pickerColor:n,onChange:a=>e(i3(a))})]})})}function g8(){return i.jsxs(H,{columnGap:4,alignItems:"center",children:[i.jsx(Oce,{}),i.jsx(Mce,{})]})}function Dce(){const e=te(),t=z(r=>r.canvas.shouldRestrictStrokesToBox),{t:n}=be();return i.jsx(Gn,{label:n("unifiedCanvas.betaLimitToBox"),isChecked:t,onChange:r=>e(p3(r.target.checked))})}function Tce(){return i.jsxs(H,{gap:4,alignItems:"center",children:[i.jsx(g8,{}),i.jsx(Dce,{})]})}function Ace(){const e=te(),{t}=be(),n=()=>e(q1());return i.jsx(rn,{size:"sm",leftIcon:i.jsx(us,{}),onClick:n,tooltip:`${t("unifiedCanvas.clearMask")} (Shift+C)`,children:t("unifiedCanvas.betaClear")})}function Nce(){const e=z(o=>o.canvas.isMaskEnabled),t=te(),{t:n}=be(),r=()=>t(pd(!e));return i.jsx(Gn,{label:`${n("unifiedCanvas.enableMask")} (H)`,isChecked:e,onChange:r})}function $ce(){const e=te(),{t}=be(),n=z(r=>r.canvas.shouldPreserveMaskedArea);return i.jsx(Gn,{label:t("unifiedCanvas.betaPreserveMasked"),isChecked:n,onChange:r=>e(a3(r.target.checked))})}function zce(){return i.jsxs(H,{gap:4,alignItems:"center",children:[i.jsx(g8,{}),i.jsx(Nce,{}),i.jsx($ce,{}),i.jsx(Ace,{})]})}function Lce(){const e=z(r=>r.canvas.shouldDarkenOutsideBoundingBox),t=te(),{t:n}=be();return i.jsx(Gn,{label:n("unifiedCanvas.betaDarkenOutside"),isChecked:e,onChange:r=>t(u3(r.target.checked))})}function Bce(){const e=z(r=>r.canvas.shouldShowGrid),t=te(),{t:n}=be();return i.jsx(Gn,{label:n("unifiedCanvas.showGrid"),isChecked:e,onChange:r=>t(c3(r.target.checked))})}function Fce(){const e=z(o=>o.canvas.shouldSnapToGrid),t=te(),{t:n}=be(),r=o=>t(Wu(o.target.checked));return i.jsx(Gn,{label:`${n("unifiedCanvas.snapToGrid")} (N)`,isChecked:e,onChange:r})}function Hce(){return i.jsxs(H,{alignItems:"center",gap:4,children:[i.jsx(Bce,{}),i.jsx(Fce,{}),i.jsx(Lce,{})]})}const Wce=fe([mn],e=>{const{tool:t,layer:n}=e;return{tool:t,layer:n}},{memoizeOptions:{resultEqualityCheck:Qt}});function Vce(){const{tool:e,layer:t}=z(Wce);return i.jsxs(H,{height:8,minHeight:8,maxHeight:8,alignItems:"center",children:[t=="base"&&["brush","eraser","colorPicker"].includes(e)&&i.jsx(Tce,{}),t=="mask"&&["brush","eraser","colorPicker"].includes(e)&&i.jsx(zce,{}),e=="move"&&i.jsx(Hce,{})]})}const Uce=fe([mn],e=>{const{shouldAutoSave:t,shouldCropToBoundingBoxOnSave:n,shouldShowCanvasDebugInfo:r,shouldShowIntermediates:o,shouldAntialias:s}=e;return{shouldAutoSave:t,shouldCropToBoundingBoxOnSave:n,shouldShowCanvasDebugInfo:r,shouldShowIntermediates:o,shouldAntialias:s}},{memoizeOptions:{resultEqualityCheck:Qt}}),Gce=()=>{const e=te(),{t}=be(),{shouldAutoSave:n,shouldCropToBoundingBoxOnSave:r,shouldShowCanvasDebugInfo:o,shouldShowIntermediates:s,shouldAntialias:a}=z(Uce);return i.jsx(gl,{isLazy:!1,triggerComponent:i.jsx(Le,{tooltip:t("unifiedCanvas.canvasSettings"),tooltipProps:{placement:"bottom"},"aria-label":t("unifiedCanvas.canvasSettings"),icon:i.jsx(Wb,{})}),children:i.jsxs(H,{direction:"column",gap:2,children:[i.jsx(Gn,{label:t("unifiedCanvas.showIntermediates"),isChecked:s,onChange:c=>e(l3(c.target.checked))}),i.jsx(Gn,{label:t("unifiedCanvas.autoSaveToGallery"),isChecked:n,onChange:c=>e(d3(c.target.checked))}),i.jsx(Gn,{label:t("unifiedCanvas.saveBoxRegionOnly"),isChecked:r,onChange:c=>e(f3(c.target.checked))}),i.jsx(Gn,{label:t("unifiedCanvas.showCanvasDebugInfo"),isChecked:o,onChange:c=>e(h3(c.target.checked))}),i.jsx(Gn,{label:t("unifiedCanvas.antialiasing"),isChecked:a,onChange:c=>e(m3(c.target.checked))}),i.jsx(h8,{})]})})};function qce(){const e=z(ir),t=Ia(),{isClipboardAPIAvailable:n}=Oy(),r=z(c=>c.system.isProcessing),o=te(),{t:s}=be();nt(["meta+c","ctrl+c"],()=>{a()},{enabled:()=>!e&&n,preventDefault:!0},[t,r,n]);const a=f.useCallback(()=>{n&&o(w3())},[o,n]);return n?i.jsx(Le,{"aria-label":`${s("unifiedCanvas.copyToClipboard")} (Cmd/Ctrl+C)`,tooltip:`${s("unifiedCanvas.copyToClipboard")} (Cmd/Ctrl+C)`,icon:i.jsx(Fc,{}),onClick:a,isDisabled:e}):null}function Kce(){const e=te(),{t}=be(),n=Ia(),r=z(ir);nt(["shift+d"],()=>{o()},{enabled:()=>!r,preventDefault:!0},[n]);const o=()=>{e(S3())};return i.jsx(Le,{"aria-label":`${t("unifiedCanvas.downloadAsImage")} (Shift+D)`,tooltip:`${t("unifiedCanvas.downloadAsImage")} (Shift+D)`,icon:i.jsx(Bb,{}),onClick:o,isDisabled:r})}function Yce(){const e=z(ir),{getUploadButtonProps:t,getUploadInputProps:n}=Vm({postUploadAction:{type:"SET_CANVAS_INITIAL_IMAGE"}}),{t:r}=be();return i.jsxs(i.Fragment,{children:[i.jsx(Le,{"aria-label":r("common.upload"),tooltip:r("common.upload"),icon:i.jsx(Md,{}),isDisabled:e,...t()}),i.jsx("input",{...n()})]})}const Xce=fe([mn,ir],(e,t)=>{const{layer:n,isMaskEnabled:r}=e;return{layer:n,isMaskEnabled:r,isStaging:t}},{memoizeOptions:{resultEqualityCheck:Qt}});function Qce(){const e=te(),{t}=be(),{layer:n,isMaskEnabled:r,isStaging:o}=z(Xce),s=()=>{e(Np(n==="mask"?"base":"mask"))};nt(["q"],()=>{s()},{enabled:()=>!o,preventDefault:!0},[n]);const a=c=>{const d=c;e(Np(d)),d==="mask"&&!r&&e(pd(!0))};return i.jsx(Yr,{tooltip:`${t("unifiedCanvas.layer")} (Q)`,"aria-label":`${t("unifiedCanvas.layer")} (Q)`,value:n,data:C3,onChange:a,disabled:o,w:"full"})}function Jce(){const e=te(),{t}=be(),n=Ia(),r=z(ir),o=z(a=>a.system.isProcessing);nt(["shift+m"],()=>{s()},{enabled:()=>!r,preventDefault:!0},[n,o]);const s=()=>{e(y3())};return i.jsx(Le,{"aria-label":`${t("unifiedCanvas.mergeVisible")} (Shift+M)`,tooltip:`${t("unifiedCanvas.mergeVisible")} (Shift+M)`,icon:i.jsx(v6,{}),onClick:s,isDisabled:r})}function Zce(){const e=z(s=>s.canvas.tool),t=z(ir),n=te(),{t:r}=be();nt(["v"],()=>{o()},{enabled:()=>!t,preventDefault:!0},[]);const o=()=>n(ea("move"));return i.jsx(Le,{"aria-label":`${r("unifiedCanvas.move")} (V)`,tooltip:`${r("unifiedCanvas.move")} (V)`,icon:i.jsx(u6,{}),isChecked:e==="move"||t,onClick:o})}function eue(){const e=z(s=>s.ui.shouldPinParametersPanel),t=z(s=>s.ui.shouldShowParametersPanel),n=te(),{t:r}=be(),o=()=>{n(K1(!0)),e&&n(So())};return!e||!t?i.jsxs(H,{flexDirection:"column",gap:2,children:[i.jsx(Le,{tooltip:`${r("parameters.showOptionsPanel")} (O)`,tooltipProps:{placement:"top"},"aria-label":r("parameters.showOptionsPanel"),onClick:o,children:i.jsx(Fb,{})}),i.jsx(H,{children:i.jsx(zy,{iconButton:!0})}),i.jsx(H,{children:i.jsx(Qm,{width:"100%",height:"40px",btnGroupWidth:"100%"})})]}):null}function tue(){const e=te(),{t}=be(),n=z(ir),r=()=>{e(F1()),e(em())};return i.jsx(Le,{"aria-label":t("unifiedCanvas.clearCanvas"),tooltip:t("unifiedCanvas.clearCanvas"),icon:i.jsx(us,{}),onClick:r,isDisabled:n,colorScheme:"error"})}function nue(){const e=Ia(),t=te(),{t:n}=be();nt(["r"],()=>{o()},{enabled:()=>!0,preventDefault:!0},[e]);const r=f8(()=>o(!1),()=>o(!0)),o=(s=!1)=>{const a=Ia();if(!a)return;const c=a.getClientRect({skipTransform:!0});t(b3({contentRect:c,shouldScaleTo1:s}))};return i.jsx(Le,{"aria-label":`${n("unifiedCanvas.resetView")} (R)`,tooltip:`${n("unifiedCanvas.resetView")} (R)`,icon:i.jsx(f6,{}),onClick:r})}function rue(){const e=z(ir),t=Ia(),n=z(a=>a.system.isProcessing),r=te(),{t:o}=be();nt(["shift+s"],()=>{s()},{enabled:()=>!e,preventDefault:!0},[t,n]);const s=()=>{r(x3())};return i.jsx(Le,{"aria-label":`${o("unifiedCanvas.saveToGallery")} (Shift+S)`,tooltip:`${o("unifiedCanvas.saveToGallery")} (Shift+S)`,icon:i.jsx(_m,{}),onClick:s,isDisabled:e})}const oue=fe([mn,ir,mo],(e,t,n)=>{const{isProcessing:r}=n,{tool:o}=e;return{tool:o,isStaging:t,isProcessing:r}},{memoizeOptions:{resultEqualityCheck:Qt}}),sue=()=>{const e=te(),{t}=be(),{tool:n,isStaging:r}=z(oue);nt(["b"],()=>{o()},{enabled:()=>!r,preventDefault:!0},[]),nt(["e"],()=>{s()},{enabled:()=>!r,preventDefault:!0},[n]),nt(["c"],()=>{a()},{enabled:()=>!r,preventDefault:!0},[n]),nt(["shift+f"],()=>{c()},{enabled:()=>!r,preventDefault:!0}),nt(["delete","backspace"],()=>{d()},{enabled:()=>!r,preventDefault:!0});const o=()=>e(ea("brush")),s=()=>e(ea("eraser")),a=()=>e(ea("colorPicker")),c=()=>e(g3()),d=()=>e(v3());return i.jsxs(H,{flexDirection:"column",gap:2,children:[i.jsxs(nr,{children:[i.jsx(Le,{"aria-label":`${t("unifiedCanvas.brush")} (B)`,tooltip:`${t("unifiedCanvas.brush")} (B)`,icon:i.jsx(b6,{}),isChecked:n==="brush"&&!r,onClick:o,isDisabled:r}),i.jsx(Le,{"aria-label":`${t("unifiedCanvas.eraser")} (E)`,tooltip:`${t("unifiedCanvas.eraser")} (B)`,icon:i.jsx(p6,{}),isChecked:n==="eraser"&&!r,isDisabled:r,onClick:s})]}),i.jsxs(nr,{children:[i.jsx(Le,{"aria-label":`${t("unifiedCanvas.fillBoundingBox")} (Shift+F)`,tooltip:`${t("unifiedCanvas.fillBoundingBox")} (Shift+F)`,icon:i.jsx(g6,{}),isDisabled:r,onClick:c}),i.jsx(Le,{"aria-label":`${t("unifiedCanvas.eraseBoundingBox")} (Del/Backspace)`,tooltip:`${t("unifiedCanvas.eraseBoundingBox")} (Del/Backspace)`,icon:i.jsx(ml,{style:{transform:"rotate(45deg)"}}),isDisabled:r,onClick:d})]}),i.jsx(Le,{"aria-label":`${t("unifiedCanvas.colorPicker")} (C)`,tooltip:`${t("unifiedCanvas.colorPicker")} (C)`,icon:i.jsx(m6,{}),isChecked:n==="colorPicker"&&!r,isDisabled:r,onClick:a,width:"max-content"})]})},aue=()=>i.jsxs(H,{flexDirection:"column",rowGap:2,width:"min-content",children:[i.jsx(Qce,{}),i.jsx(sue,{}),i.jsxs(H,{gap:2,children:[i.jsx(Zce,{}),i.jsx(nue,{})]}),i.jsxs(H,{columnGap:2,children:[i.jsx(Jce,{}),i.jsx(rue,{})]}),i.jsxs(H,{columnGap:2,children:[i.jsx(qce,{}),i.jsx(Kce,{})]}),i.jsxs(H,{gap:2,children:[i.jsx(m8,{}),i.jsx(p8,{})]}),i.jsxs(H,{gap:2,children:[i.jsx(Yce,{}),i.jsx(tue,{})]}),i.jsx(Gce,{}),i.jsx(eue,{})]}),iue=fe([mn,La],(e,t)=>{const{doesCanvasNeedScaling:n}=e,{shouldUseCanvasBetaLayout:r}=t;return{doesCanvasNeedScaling:n,shouldUseCanvasBetaLayout:r}},Ge),av={id:"canvas-intial-image",actionType:"SET_CANVAS_INITIAL_IMAGE"},lue=()=>{const e=te(),{doesCanvasNeedScaling:t,shouldUseCanvasBetaLayout:n}=z(iue),{isOver:r,setNodeRef:o,active:s}=A1({id:"unifiedCanvas",data:av});return f.useLayoutEffect(()=>{const a=()=>{e(So())};return window.addEventListener("resize",a),()=>window.removeEventListener("resize",a)},[e]),n?i.jsx(Oe,{layerStyle:"first",ref:o,tabIndex:0,sx:{w:"full",h:"full",p:4,borderRadius:"base"},children:i.jsxs(H,{sx:{w:"full",h:"full",gap:4},children:[i.jsx(aue,{}),i.jsxs(H,{sx:{flexDir:"column",w:"full",h:"full",gap:4,position:"relative"},children:[i.jsx(Vce,{}),i.jsxs(Oe,{sx:{w:"full",h:"full",position:"relative"},children:[t?i.jsx(f_,{}):i.jsx(d_,{}),Ep(av,s)&&i.jsx(nh,{isOver:r,label:"Set Canvas Initial Image"})]})]})]})}):i.jsx(Oe,{ref:o,tabIndex:-1,sx:{layerStyle:"first",w:"full",h:"full",p:4,borderRadius:"base"},children:i.jsxs(H,{sx:{flexDirection:"column",alignItems:"center",gap:4,w:"full",h:"full"},children:[i.jsx(Ece,{}),i.jsx(H,{sx:{flexDirection:"column",alignItems:"center",justifyContent:"center",gap:4,w:"full",h:"full"},children:i.jsxs(Oe,{sx:{w:"full",h:"full",position:"relative"},children:[t?i.jsx(f_,{}):i.jsx(d_,{}),Ep(av,s)&&i.jsx(nh,{isOver:r,label:"Set Canvas Initial Image"})]})})]})})},cue=f.memo(lue),uue=fe([Ye],({generation:e})=>{const{infillMethod:t}=e;return{infillMethod:t}},Ge),due=()=>{const e=te(),{infillMethod:t}=z(uue),{data:n,isLoading:r}=L_(),o=n==null?void 0:n.infill_methods,{t:s}=be(),a=f.useCallback(c=>{e(SD(c))},[e]);return i.jsx(Yr,{disabled:(o==null?void 0:o.length)===0,placeholder:r?"Loading...":void 0,label:s("parameters.infillMethod"),value:t,data:o??[],onChange:a})},fue=f.memo(due),pue=fe([Mi],e=>{const{tileSize:t,infillMethod:n}=e;return{tileSize:t,infillMethod:n}},Ge),hue=()=>{const e=te(),{tileSize:t,infillMethod:n}=z(pue),{t:r}=be(),o=f.useCallback(a=>{e(cw(a))},[e]),s=f.useCallback(()=>{e(cw(32))},[e]);return i.jsx(_t,{isDisabled:n!=="tile",label:r("parameters.tileSize"),min:16,max:64,sliderNumberInputProps:{max:256},value:t,onChange:o,withInput:!0,withSliderMarks:!0,withReset:!0,handleReset:s})},mue=f.memo(hue),gue=fe([mn],e=>{const{boundingBoxScaleMethod:t}=e;return{boundingBoxScale:t}},Ge),vue=()=>{const e=te(),{boundingBoxScale:t}=z(gue),{t:n}=be(),r=o=>{e(kD(o))};return i.jsx(sr,{label:n("parameters.scaleBeforeProcessing"),data:CD,value:t,onChange:r})},bue=f.memo(vue),yue=fe([Mi,mo,mn],(e,t,n)=>{const{scaledBoundingBoxDimensions:r,boundingBoxScaleMethod:o}=n;return{scaledBoundingBoxDimensions:r,isManual:o==="manual"}},Ge),xue=()=>{const e=te(),{isManual:t,scaledBoundingBoxDimensions:n}=z(yue),{t:r}=be(),o=a=>{e($p({...n,height:Math.floor(a)}))},s=()=>{e($p({...n,height:Math.floor(512)}))};return i.jsx(_t,{isDisabled:!t,label:r("parameters.scaledHeight"),min:64,max:1024,step:64,value:n.height,onChange:o,sliderNumberInputProps:{max:4096},withSliderMarks:!0,withInput:!0,withReset:!0,handleReset:s})},wue=f.memo(xue),Sue=fe([mn],e=>{const{boundingBoxScaleMethod:t,scaledBoundingBoxDimensions:n}=e;return{scaledBoundingBoxDimensions:n,isManual:t==="manual"}},Ge),Cue=()=>{const e=te(),{isManual:t,scaledBoundingBoxDimensions:n}=z(Sue),{t:r}=be(),o=a=>{e($p({...n,width:Math.floor(a)}))},s=()=>{e($p({...n,width:Math.floor(512)}))};return i.jsx(_t,{isDisabled:!t,label:r("parameters.scaledWidth"),min:64,max:1024,step:64,value:n.width,onChange:o,sliderNumberInputProps:{max:4096},withSliderMarks:!0,withInput:!0,withReset:!0,handleReset:s})},kue=f.memo(Cue),_ue=()=>{const{t:e}=be();return i.jsx(Oo,{label:e("parameters.infillScalingHeader"),children:i.jsxs(H,{sx:{gap:2,flexDirection:"column"},children:[i.jsx(fue,{}),i.jsx(mue,{}),i.jsx(bue,{}),i.jsx(kue,{}),i.jsx(wue,{})]})})},Pue=f.memo(_ue);function jue(){const e=te(),t=z(r=>r.generation.seamBlur),{t:n}=be();return i.jsx(_t,{label:n("parameters.seamBlur"),min:0,max:64,sliderNumberInputProps:{max:512},value:t,onChange:r=>{e(uw(r))},withInput:!0,withSliderMarks:!0,withReset:!0,handleReset:()=>{e(uw(16))}})}function Iue(){const e=te(),{t}=be(),n=z(r=>r.generation.seamSize);return i.jsx(_t,{label:t("parameters.seamSize"),min:1,max:256,sliderNumberInputProps:{max:512},value:n,onChange:r=>{e(dw(r))},withInput:!0,withSliderMarks:!0,withReset:!0,handleReset:()=>e(dw(96))})}function Eue(){const{t:e}=be(),t=z(r=>r.generation.seamSteps),n=te();return i.jsx(_t,{label:e("parameters.seamSteps"),min:1,max:100,sliderNumberInputProps:{max:999},value:t,onChange:r=>{n(fw(r))},withInput:!0,withSliderMarks:!0,withReset:!0,handleReset:()=>{n(fw(30))}})}function Oue(){const e=te(),{t}=be(),n=z(r=>r.generation.seamStrength);return i.jsx(_t,{label:t("parameters.seamStrength"),min:.01,max:.99,step:.01,value:n,onChange:r=>{e(pw(r))},withInput:!0,withSliderMarks:!0,withReset:!0,handleReset:()=>{e(pw(.7))}})}const Rue=()=>{const{t:e}=be();return i.jsxs(Oo,{label:e("parameters.seamCorrectionHeader"),children:[i.jsx(Iue,{}),i.jsx(jue,{}),i.jsx(Oue,{}),i.jsx(Eue,{})]})},Mue=f.memo(Rue),Due=fe([Ye,ir],({canvas:e,generation:t},n)=>{const{boundingBoxDimensions:r}=e,{aspectRatio:o}=t;return{boundingBoxDimensions:r,isStaging:n,aspectRatio:o}},Ge),Tue=()=>{const e=te(),{boundingBoxDimensions:t,isStaging:n,aspectRatio:r}=z(Due),{t:o}=be(),s=c=>{if(e(Js({...t,height:Math.floor(c)})),r){const d=Ss(c*r,64);e(Js({width:d,height:Math.floor(c)}))}},a=()=>{if(e(Js({...t,height:Math.floor(512)})),r){const c=Ss(512*r,64);e(Js({width:c,height:Math.floor(512)}))}};return i.jsx(_t,{label:o("parameters.boundingBoxHeight"),min:64,max:1024,step:64,value:t.height,onChange:s,isDisabled:n,sliderNumberInputProps:{max:4096},withSliderMarks:!0,withInput:!0,withReset:!0,handleReset:a})},Aue=f.memo(Tue),Nue=fe([Ye,ir],({canvas:e,generation:t},n)=>{const{boundingBoxDimensions:r}=e,{aspectRatio:o}=t;return{boundingBoxDimensions:r,isStaging:n,aspectRatio:o}},Ge),$ue=()=>{const e=te(),{boundingBoxDimensions:t,isStaging:n,aspectRatio:r}=z(Nue),{t:o}=be(),s=c=>{if(e(Js({...t,width:Math.floor(c)})),r){const d=Ss(c/r,64);e(Js({width:Math.floor(c),height:d}))}},a=()=>{if(e(Js({...t,width:Math.floor(512)})),r){const c=Ss(512/r,64);e(Js({width:Math.floor(512),height:c}))}};return i.jsx(_t,{label:o("parameters.boundingBoxWidth"),min:64,max:1024,step:64,value:t.width,onChange:s,isDisabled:n,sliderNumberInputProps:{max:4096},withSliderMarks:!0,withInput:!0,withReset:!0,handleReset:a})},zue=f.memo($ue);function p_(){const e=te(),{t}=be();return i.jsxs(H,{sx:{gap:2,p:4,borderRadius:4,flexDirection:"column",w:"full",bg:"base.150",_dark:{bg:"base.750"}},children:[i.jsxs(H,{alignItems:"center",gap:2,children:[i.jsx(tt,{sx:{fontSize:"sm",width:"full",color:"base.700",_dark:{color:"base.300"}},children:t("parameters.aspectRatio")}),i.jsx(fl,{}),i.jsx(PO,{}),i.jsx(Le,{tooltip:t("ui.swapSizes"),"aria-label":t("ui.swapSizes"),size:"sm",icon:i.jsx(sO,{}),fontSize:20,onClick:()=>e(_D())})]}),i.jsx(zue,{}),i.jsx(Aue,{})]})}const Lue=fe(Ye,({ui:e,generation:t})=>{const{shouldUseSliders:n}=e,{shouldRandomizeSeed:r}=t;return{shouldUseSliders:n,activeLabel:r?void 0:"Manual Seed"}},Ge),Bue=()=>{const{shouldUseSliders:e,activeLabel:t}=z(Lue);return i.jsx(Oo,{label:"General",activeLabel:t,defaultIsOpen:!0,children:i.jsxs(H,{sx:{flexDirection:"column",gap:3},children:[e?i.jsxs(i.Fragment,{children:[i.jsx(wi,{}),i.jsx(Ci,{}),i.jsx(xi,{}),i.jsx(Si,{}),i.jsx(Oe,{pt:2,children:i.jsx(ki,{})}),i.jsx(p_,{})]}):i.jsxs(i.Fragment,{children:[i.jsxs(H,{gap:3,children:[i.jsx(wi,{}),i.jsx(Ci,{}),i.jsx(xi,{})]}),i.jsx(Si,{}),i.jsx(Oe,{pt:2,children:i.jsx(ki,{})}),i.jsx(p_,{})]}),i.jsx(AO,{})]})})},Fue=f.memo(Bue),v8=()=>i.jsxs(i.Fragment,{children:[i.jsx(Fd,{}),i.jsx(Ld,{}),i.jsx(Hd,{}),i.jsx(Fue,{}),i.jsx(Hy,{}),i.jsx(By,{}),i.jsx(zd,{}),i.jsx(Wy,{}),i.jsx(Mue,{}),i.jsx(Pue,{}),i.jsx(Fy,{})]}),Hue=()=>i.jsxs(H,{sx:{gap:4,w:"full",h:"full"},children:[i.jsx(Ly,{children:i.jsx(v8,{})}),i.jsx(cue,{})]}),Wue=f.memo(Hue),Vue=[{id:"txt2img",translationKey:"common.txt2img",icon:i.jsx(Kr,{as:ZH,sx:{boxSize:6,pointerEvents:"none"}}),content:i.jsx(Cie,{})},{id:"img2img",translationKey:"common.img2img",icon:i.jsx(Kr,{as:al,sx:{boxSize:6,pointerEvents:"none"}}),content:i.jsx(Coe,{})},{id:"unifiedCanvas",translationKey:"common.unifiedCanvas",icon:i.jsx(Kr,{as:See,sx:{boxSize:6,pointerEvents:"none"}}),content:i.jsx(Wue,{})},{id:"nodes",translationKey:"common.nodes",icon:i.jsx(Kr,{as:wee,sx:{boxSize:6,pointerEvents:"none"}}),content:i.jsx(yie,{})},{id:"modelManager",translationKey:"modelManager.modelManager",icon:i.jsx(Kr,{as:GH,sx:{boxSize:6,pointerEvents:"none"}}),content:i.jsx(Sse,{})}],Uue=fe([aO,mo],(e,t)=>{const{disabledTabs:n}=e,{isNodesEnabled:r}=t;return Vue.filter(s=>s.id==="nodes"?r&&!n.includes(s.id):!n.includes(s.id))},{memoizeOptions:{resultEqualityCheck:Qt}}),Gue=350,iv=20,b8=["modelManager"],que=()=>{const e=z(PD),t=z(Kn),n=z(Uue),{shouldPinGallery:r,shouldPinParametersPanel:o,shouldShowGallery:s}=z(y=>y.ui),{t:a}=be(),c=te();nt("f",()=>{c(jD()),(r||o)&&c(So())},[r,o]);const d=f.useCallback(()=>{t==="unifiedCanvas"&&c(So())},[c,t]),p=f.useCallback(y=>{y.target instanceof HTMLElement&&y.target.blur()},[]),h=f.useMemo(()=>n.map(y=>i.jsx(wn,{hasArrow:!0,label:String(a(y.translationKey)),placement:"end",children:i.jsxs(wc,{onClick:p,children:[i.jsx(L3,{children:String(a(y.translationKey))}),y.icon]})},y.id)),[n,a,p]),m=f.useMemo(()=>n.map(y=>i.jsx(Cm,{children:y.content},y.id)),[n]),{ref:v,minSizePct:b}=Uee(Gue,iv,"app"),w=f.useCallback(y=>{const S=ID[y];S&&c(ql(S))},[c]);return i.jsxs(Ed,{defaultIndex:e,index:e,onChange:w,sx:{flexGrow:1,gap:4},isLazy:!0,children:[i.jsxs(Od,{sx:{pt:2,gap:4,flexDir:"column"},children:[h,i.jsx(fl,{}),i.jsx(jee,{})]}),i.jsxs(Ay,{id:"app",autoSaveId:"app",direction:"horizontal",style:{height:"100%",width:"100%"},children:[i.jsx(sd,{id:"main",children:i.jsx(km,{style:{height:"100%",width:"100%"},children:m})}),r&&s&&!b8.includes(t)&&i.jsxs(i.Fragment,{children:[i.jsx(OO,{}),i.jsx(sd,{ref:v,onResize:d,id:"gallery",order:3,defaultSize:b>iv?b:iv,minSize:b,maxSize:50,children:i.jsx(nO,{})})]})]})]})},Kue=f.memo(que),Yue=fe([Kn,La],(e,t)=>{const{shouldPinGallery:n,shouldShowGallery:r}=t;return{shouldPinGallery:n,shouldShowGalleryButton:b8.includes(e)?!1:!r}},{memoizeOptions:{resultEqualityCheck:Qt}}),Xue=()=>{const{t:e}=be(),{shouldPinGallery:t,shouldShowGalleryButton:n}=z(Yue),r=te(),o=()=>{r(vv(!0)),t&&r(So())};return n?i.jsx(Le,{tooltip:"Show Gallery (G)",tooltipProps:{placement:"top"},"aria-label":e("accessibility.showGallery"),onClick:o,sx:{pos:"absolute",top:"50%",transform:"translate(0, -50%)",p:0,insetInlineEnd:0,px:3,h:48,w:8,borderStartEndRadius:0,borderEndEndRadius:0,shadow:"2xl"},children:i.jsx(Cee,{})}):null},Que=f.memo(Xue),lv={borderStartStartRadius:0,borderEndStartRadius:0,shadow:"2xl"},Jue=fe([La,Kn],(e,t)=>{const{shouldPinParametersPanel:n,shouldUseCanvasBetaLayout:r,shouldShowParametersPanel:o}=e,s=r&&t==="unifiedCanvas",a=!s&&(!n||!o),c=!s&&!o&&["txt2img","img2img","unifiedCanvas"].includes(t);return{shouldPinParametersPanel:n,shouldShowParametersPanelButton:c,shouldShowProcessButtons:a}},{memoizeOptions:{resultEqualityCheck:Qt}}),Zue=()=>{const e=te(),{t}=be(),{shouldShowProcessButtons:n,shouldShowParametersPanelButton:r,shouldPinParametersPanel:o}=z(Jue),s=()=>{e(K1(!0)),o&&e(So())};return r?i.jsxs(H,{pos:"absolute",transform:"translate(0, -50%)",minW:8,top:"50%",insetInlineStart:"4.5rem",direction:"column",gap:2,children:[i.jsx(Le,{tooltip:"Show Options Panel (O)",tooltipProps:{placement:"top"},"aria-label":t("accessibility.showOptionsPanel"),onClick:s,sx:lv,children:i.jsx(Fb,{})}),n&&i.jsxs(i.Fragment,{children:[i.jsx(zy,{iconButton:!0,sx:lv}),i.jsx(Qm,{sx:lv})]})]}):null},ede=f.memo(Zue),tde=fe([La,Kn],(e,t)=>{const{shouldPinParametersPanel:n,shouldShowParametersPanel:r}=e;return{activeTabName:t,shouldPinParametersPanel:n,shouldShowParametersPanel:r}},Ge),nde=()=>{const e=te(),{shouldPinParametersPanel:t,shouldShowParametersPanel:n,activeTabName:r}=z(tde),o=()=>{e(K1(!1))},s=z(c=>c.generation.model),a=f.useMemo(()=>r==="txt2img"?s&&s.base_model==="sdxl"?i.jsx(ZO,{}):i.jsx(e8,{}):r==="img2img"?s&&s.base_model==="sdxl"?i.jsx(IO,{}):i.jsx(NO,{}):r==="unifiedCanvas"?i.jsx(v8,{}):null,[r,s]);return t?null:i.jsx(i6,{direction:"left",isResizable:!1,isOpen:n,onClose:o,children:i.jsxs(H,{sx:{flexDir:"column",h:"full",w:$y,gap:2,position:"relative",flexShrink:0,overflowY:"auto"},children:[i.jsxs(H,{paddingBottom:4,justifyContent:"space-between",alignItems:"center",children:[i.jsx(oO,{}),i.jsx(EO,{})]}),i.jsx(H,{sx:{gap:2,flexDirection:"column",h:"full",w:"full"},children:a})]})})},rde=f.memo(nde),ode=()=>{const{data:e,isFetching:t}=Zh(),{isOpen:n,onClose:r,handleAddToBoard:o,image:s}=f.useContext(T_),[a,c]=f.useState(),d=f.useRef(null),p=e==null?void 0:e.find(h=>h.board_id===(s==null?void 0:s.board_id));return i.jsx(Pd,{isOpen:n,leastDestructiveRef:d,onClose:r,isCentered:!0,children:i.jsx(Ma,{children:i.jsxs(jd,{children:[i.jsx(Ra,{fontSize:"lg",fontWeight:"bold",children:p?"Move Image to Board":"Add Image to Board"}),i.jsx(Da,{children:i.jsx(Oe,{children:i.jsxs(H,{direction:"column",gap:3,children:[p&&i.jsxs(tt,{children:["Moving this image from"," ",i.jsx("strong",{children:p.board_name})," to"]}),t?i.jsx(dl,{}):i.jsx(sr,{placeholder:"Select Board",onChange:h=>c(h),value:a,data:(e??[]).map(h=>({label:h.board_name,value:h.board_id}))})]})})}),i.jsxs(Oa,{children:[i.jsx(rn,{onClick:r,children:"Cancel"}),i.jsx(rn,{isDisabled:!a,colorScheme:"accent",onClick:()=>{a&&o(a)},ml:3,children:p?"Move":"Add"})]})]})})})},sde=f.memo(ode),ade=fe([e=>e.hotkeys,e=>e.ui],(e,t)=>{const{shift:n}=e,{shouldPinParametersPanel:r,shouldPinGallery:o}=t;return{shift:n,shouldPinGallery:o,shouldPinParametersPanel:r}},{memoizeOptions:{resultEqualityCheck:Qt}}),ide=()=>{const e=te(),{shift:t,shouldPinParametersPanel:n,shouldPinGallery:r}=z(ade),o=z(Kn);return nt("*",()=>{n6("shift")?!t&&e(_o(!0)):t&&e(_o(!1))},{keyup:!0,keydown:!0},[t]),nt("o",()=>{e(ED()),o==="unifiedCanvas"&&n&&e(So())}),nt(["shift+o"],()=>{e(OD()),o==="unifiedCanvas"&&e(So())}),nt("g",()=>{e(RD()),o==="unifiedCanvas"&&r&&e(So())}),nt(["shift+g"],()=>{e(D_()),o==="unifiedCanvas"&&e(So())}),nt("1",()=>{e(ql("txt2img"))}),nt("2",()=>{e(ql("img2img"))}),nt("3",()=>{e(ql("unifiedCanvas"))}),nt("4",()=>{e(ql("nodes"))}),null},lde=f.memo(ide),cde={},ude=({config:e=cde,headerComponent:t})=>{const n=z(V5),r=nF(),o=te();return f.useEffect(()=>{Ln.changeLanguage(n)},[n]),f.useEffect(()=>{G_(e)&&(r.info({namespace:"App",config:e},"Received config"),o(MD(e)))},[o,e,r]),f.useEffect(()=>{o(DD())},[o]),i.jsxs(i.Fragment,{children:[i.jsxs(rl,{w:"100vw",h:"100vh",position:"relative",overflow:"hidden",children:[i.jsx(pH,{children:i.jsxs(rl,{sx:{gap:4,p:4,gridAutoRows:"min-content auto",w:"full",h:"full"},children:[t||i.jsx(yee,{}),i.jsx(H,{sx:{gap:4,w:"full",h:"full"},children:i.jsx(Kue,{})})]})}),i.jsx(qZ,{}),i.jsx(rde,{}),i.jsx(Vu,{children:i.jsx(ede,{})}),i.jsx(Vu,{children:i.jsx(Que,{})})]}),i.jsx(QZ,{}),i.jsx(sde,{}),i.jsx(rF,{}),i.jsx(lde,{})]})},gde=f.memo(ude);export{gde as default}; diff --git a/invokeai/frontend/web/dist/assets/MantineProvider-8184f020.js b/invokeai/frontend/web/dist/assets/MantineProvider-8184f020.js new file mode 100644 index 0000000000..cc098c35c0 --- /dev/null +++ b/invokeai/frontend/web/dist/assets/MantineProvider-8184f020.js @@ -0,0 +1 @@ +import{z as p,A as d,a4 as Z,aH as xe,g1 as We,Z as De,U as E,a7 as q,R as z,V as R,a1 as _e,a0 as Be,$ as Ce,_ as Ge,Y as Ue,g2 as Ve,g3 as Ze,fU as qe,ab as j,fS as B,f_ as Xe}from"./index-89941396.js";function Ye(e,t){return`${e} returned \`undefined\`. Seems you forgot to wrap component within ${t}`}function M(e={}){const{name:t,strict:r=!0,hookName:o="useContext",providerName:a="Provider",errorMessage:n,defaultValue:s}=e,i=p.createContext(s);i.displayName=t;function l(){var c;const u=p.useContext(i);if(!u&&r){const f=new Error(n??Ye(o,a));throw f.name="ContextError",(c=Error.captureStackTrace)==null||c.call(Error,f,l),f}return u}return[i.Provider,l,i]}var[Je,Ke]=M({strict:!1,name:"PortalManagerContext"});function Qe(e){const{children:t,zIndex:r}=e;return d.jsx(Je,{value:{zIndex:r},children:t})}Qe.displayName="PortalManager";var[ke,et]=M({strict:!1,name:"PortalContext"}),Y="chakra-portal",tt=".chakra-portal",rt=e=>d.jsx("div",{className:"chakra-portal-zIndex",style:{position:"absolute",zIndex:e.zIndex,top:0,left:0,right:0},children:e.children}),nt=e=>{const{appendToParentPortal:t,children:r}=e,[o,a]=p.useState(null),n=p.useRef(null),[,s]=p.useState({});p.useEffect(()=>s({}),[]);const i=et(),l=Ke();Z(()=>{if(!o)return;const u=o.ownerDocument,f=t?i??u.body:u.body;if(!f)return;n.current=u.createElement("div"),n.current.className=Y,f.appendChild(n.current),s({});const y=n.current;return()=>{f.contains(y)&&f.removeChild(y)}},[o]);const c=l!=null&&l.zIndex?d.jsx(rt,{zIndex:l==null?void 0:l.zIndex,children:r}):r;return n.current?xe.createPortal(d.jsx(ke,{value:n.current,children:c}),n.current):d.jsx("span",{ref:u=>{u&&a(u)}})},ot=e=>{const{children:t,containerRef:r,appendToParentPortal:o}=e,a=r.current,n=a??(typeof window<"u"?document.body:void 0),s=p.useMemo(()=>{const l=a==null?void 0:a.ownerDocument.createElement("div");return l&&(l.className=Y),l},[a]),[,i]=p.useState({});return Z(()=>i({}),[]),Z(()=>{if(!(!s||!n))return n.appendChild(s),()=>{n.removeChild(s)}},[s,n]),n&&s?xe.createPortal(d.jsx(ke,{value:o?s:null,children:t}),s):null};function G(e){const t={appendToParentPortal:!0,...e},{containerRef:r,...o}=t;return r?d.jsx(ot,{containerRef:r,...o}):d.jsx(nt,{...o})}G.className=Y;G.selector=tt;G.displayName="Portal";function P(e,t){return r=>r.colorMode==="dark"?t:e}function Or(e){const{orientation:t,vertical:r,horizontal:o}=e;return t?t==="vertical"?r:o:{}}var at=(e,t)=>e.find(r=>r.id===t);function re(e,t){const r=we(e,t),o=r?e[r].findIndex(a=>a.id===t):-1;return{position:r,index:o}}function we(e,t){for(const[r,o]of Object.entries(e))if(at(o,t))return r}function st(e){const t=e.includes("right"),r=e.includes("left");let o="center";return t&&(o="flex-end"),r&&(o="flex-start"),{display:"flex",flexDirection:"column",alignItems:o}}function it(e){const r=e==="top"||e==="bottom"?"0 auto":void 0,o=e.includes("top")?"env(safe-area-inset-top, 0px)":void 0,a=e.includes("bottom")?"env(safe-area-inset-bottom, 0px)":void 0,n=e.includes("left")?void 0:"env(safe-area-inset-right, 0px)",s=e.includes("right")?void 0:"env(safe-area-inset-left, 0px)";return{position:"fixed",zIndex:"var(--toast-z-index, 5500)",pointerEvents:"none",display:"flex",flexDirection:"column",margin:r,top:o,bottom:a,right:n,left:s}}function lt(e,t=[]){const r=p.useRef(e);return p.useEffect(()=>{r.current=e}),p.useCallback((...o)=>{var a;return(a=r.current)==null?void 0:a.call(r,...o)},t)}function ct(e,t){const r=lt(e);p.useEffect(()=>{if(t==null)return;let o=null;return o=window.setTimeout(()=>{r()},t),()=>{o&&window.clearTimeout(o)}},[t,r])}function ne(e,t){const r=p.useRef(!1),o=p.useRef(!1);p.useEffect(()=>{if(r.current&&o.current)return e();o.current=!0},t),p.useEffect(()=>(r.current=!0,()=>{r.current=!1}),[])}var ut={initial:e=>{const{position:t}=e,r=["top","bottom"].includes(t)?"y":"x";let o=["top-right","bottom-right"].includes(t)?1:-1;return t==="bottom"&&(o=1),{opacity:0,[r]:o*24}},animate:{opacity:1,y:0,x:0,scale:1,transition:{duration:.4,ease:[.4,0,.2,1]}},exit:{opacity:0,scale:.85,transition:{duration:.2,ease:[.4,0,1,1]}}},Pe=p.memo(e=>{const{id:t,message:r,onCloseComplete:o,onRequestRemove:a,requestClose:n=!1,position:s="bottom",duration:i=5e3,containerStyle:l,motionVariants:c=ut,toastSpacing:u="0.5rem"}=e,[f,y]=p.useState(i),g=We();ne(()=>{g||o==null||o()},[g]),ne(()=>{y(i)},[i]);const v=()=>y(null),$=()=>y(i),S=()=>{g&&a()};p.useEffect(()=>{g&&n&&a()},[g,n,a]),ct(S,f);const H=p.useMemo(()=>({pointerEvents:"auto",maxWidth:560,minWidth:300,margin:u,...l}),[l,u]),N=p.useMemo(()=>st(s),[s]);return d.jsx(De.div,{layout:!0,className:"chakra-toast",variants:c,initial:"initial",animate:"animate",exit:"exit",onHoverStart:v,onHoverEnd:$,custom:{position:s},style:N,children:d.jsx(E.div,{role:"status","aria-atomic":"true",className:"chakra-toast__inner",__css:H,children:q(r,{id:t,onClose:S})})})});Pe.displayName="ToastComponent";function dt(e,t){var r;const o=e??"bottom",n={"top-start":{ltr:"top-left",rtl:"top-right"},"top-end":{ltr:"top-right",rtl:"top-left"},"bottom-start":{ltr:"bottom-left",rtl:"bottom-right"},"bottom-end":{ltr:"bottom-right",rtl:"bottom-left"}}[o];return(r=n==null?void 0:n[t])!=null?r:o}var oe={path:d.jsxs("g",{stroke:"currentColor",strokeWidth:"1.5",children:[d.jsx("path",{strokeLinecap:"round",fill:"none",d:"M9,9a3,3,0,1,1,4,2.829,1.5,1.5,0,0,0-1,1.415V14.25"}),d.jsx("path",{fill:"currentColor",strokeLinecap:"round",d:"M12,17.25a.375.375,0,1,0,.375.375A.375.375,0,0,0,12,17.25h0"}),d.jsx("circle",{fill:"none",strokeMiterlimit:"10",cx:"12",cy:"12",r:"11.25"})]}),viewBox:"0 0 24 24"},L=z((e,t)=>{const{as:r,viewBox:o,color:a="currentColor",focusable:n=!1,children:s,className:i,__css:l,...c}=e,u=R("chakra-icon",i),f=_e("Icon",e),y={w:"1em",h:"1em",display:"inline-block",lineHeight:"1em",flexShrink:0,color:a,...l,...f},g={ref:t,focusable:n,className:u,__css:y},v=o??oe.viewBox;if(r&&typeof r!="string")return d.jsx(E.svg,{as:r,...g,...c});const $=s??oe.path;return d.jsx(E.svg,{verticalAlign:"middle",viewBox:v,...g,...c,children:$})});L.displayName="Icon";function ft(e){return d.jsx(L,{viewBox:"0 0 24 24",...e,children:d.jsx("path",{fill:"currentColor",d:"M12,0A12,12,0,1,0,24,12,12.014,12.014,0,0,0,12,0Zm6.927,8.2-6.845,9.289a1.011,1.011,0,0,1-1.43.188L5.764,13.769a1,1,0,1,1,1.25-1.562l4.076,3.261,6.227-8.451A1,1,0,1,1,18.927,8.2Z"})})}function pt(e){return d.jsx(L,{viewBox:"0 0 24 24",...e,children:d.jsx("path",{fill:"currentColor",d:"M12,0A12,12,0,1,0,24,12,12.013,12.013,0,0,0,12,0Zm.25,5a1.5,1.5,0,1,1-1.5,1.5A1.5,1.5,0,0,1,12.25,5ZM14.5,18.5h-4a1,1,0,0,1,0-2h.75a.25.25,0,0,0,.25-.25v-4.5a.25.25,0,0,0-.25-.25H10.5a1,1,0,0,1,0-2h1a2,2,0,0,1,2,2v4.75a.25.25,0,0,0,.25.25h.75a1,1,0,1,1,0,2Z"})})}function ae(e){return d.jsx(L,{viewBox:"0 0 24 24",...e,children:d.jsx("path",{fill:"currentColor",d:"M11.983,0a12.206,12.206,0,0,0-8.51,3.653A11.8,11.8,0,0,0,0,12.207,11.779,11.779,0,0,0,11.8,24h.214A12.111,12.111,0,0,0,24,11.791h0A11.766,11.766,0,0,0,11.983,0ZM10.5,16.542a1.476,1.476,0,0,1,1.449-1.53h.027a1.527,1.527,0,0,1,1.523,1.47,1.475,1.475,0,0,1-1.449,1.53h-.027A1.529,1.529,0,0,1,10.5,16.542ZM11,12.5v-6a1,1,0,0,1,2,0v6a1,1,0,1,1-2,0Z"})})}var[mt,J]=M({name:"AlertContext",hookName:"useAlertContext",providerName:""}),[gt,K]=M({name:"AlertStylesContext",hookName:"useAlertStyles",providerName:""}),je={info:{icon:pt,colorScheme:"blue"},warning:{icon:ae,colorScheme:"orange"},success:{icon:ft,colorScheme:"green"},error:{icon:ae,colorScheme:"red"},loading:{icon:Be,colorScheme:"blue"}};function bt(e){return je[e].colorScheme}function yt(e){return je[e].icon}var Ee=z(function(t,r){const o=K(),{status:a}=J(),n={display:"inline",...o.description};return d.jsx(E.div,{ref:r,"data-status":a,...t,className:R("chakra-alert__desc",t.className),__css:n})});Ee.displayName="AlertDescription";function Ae(e){const{status:t}=J(),r=yt(t),o=K(),a=t==="loading"?o.spinner:o.icon;return d.jsx(E.span,{display:"inherit","data-status":t,...e,className:R("chakra-alert__icon",e.className),__css:a,children:e.children||d.jsx(r,{h:"100%",w:"100%"})})}Ae.displayName="AlertIcon";var Ne=z(function(t,r){const o=K(),{status:a}=J();return d.jsx(E.div,{ref:r,"data-status":a,...t,className:R("chakra-alert__title",t.className),__css:o.title})});Ne.displayName="AlertTitle";var $e=z(function(t,r){var o;const{status:a="info",addRole:n=!0,...s}=Ce(t),i=(o=t.colorScheme)!=null?o:bt(a),l=Ge("Alert",{...t,colorScheme:i}),c={width:"100%",display:"flex",alignItems:"center",position:"relative",overflow:"hidden",...l.container};return d.jsx(mt,{value:{status:a},children:d.jsx(gt,{value:l,children:d.jsx(E.div,{"data-status":a,role:n?"alert":void 0,ref:r,...s,className:R("chakra-alert",t.className),__css:c})})})});$e.displayName="Alert";function ht(e){return d.jsx(L,{focusable:"false","aria-hidden":!0,...e,children:d.jsx("path",{fill:"currentColor",d:"M.439,21.44a1.5,1.5,0,0,0,2.122,2.121L11.823,14.3a.25.25,0,0,1,.354,0l9.262,9.263a1.5,1.5,0,1,0,2.122-2.121L14.3,12.177a.25.25,0,0,1,0-.354l9.263-9.262A1.5,1.5,0,0,0,21.439.44L12.177,9.7a.25.25,0,0,1-.354,0L2.561.44A1.5,1.5,0,0,0,.439,2.561L9.7,11.823a.25.25,0,0,1,0,.354Z"})})}var Te=z(function(t,r){const o=_e("CloseButton",t),{children:a,isDisabled:n,__css:s,...i}=Ce(t),l={outline:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0};return d.jsx(E.button,{type:"button","aria-label":"Close",ref:r,disabled:n,__css:{...l,...o,...s},...i,children:a||d.jsx(ht,{width:"1em",height:"1em"})})});Te.displayName="CloseButton";var vt={top:[],"top-left":[],"top-right":[],"bottom-left":[],bottom:[],"bottom-right":[]},C=St(vt);function St(e){let t=e;const r=new Set,o=a=>{t=a(t),r.forEach(n=>n())};return{getState:()=>t,subscribe:a=>(r.add(a),()=>{o(()=>e),r.delete(a)}),removeToast:(a,n)=>{o(s=>({...s,[n]:s[n].filter(i=>i.id!=a)}))},notify:(a,n)=>{const s=xt(a,n),{position:i,id:l}=s;return o(c=>{var u,f;const g=i.includes("top")?[s,...(u=c[i])!=null?u:[]]:[...(f=c[i])!=null?f:[],s];return{...c,[i]:g}}),l},update:(a,n)=>{a&&o(s=>{const i={...s},{position:l,index:c}=re(i,a);return l&&c!==-1&&(i[l][c]={...i[l][c],...n,message:Ie(n)}),i})},closeAll:({positions:a}={})=>{o(n=>(a??["bottom","bottom-right","bottom-left","top","top-left","top-right"]).reduce((l,c)=>(l[c]=n[c].map(u=>({...u,requestClose:!0})),l),{...n}))},close:a=>{o(n=>{const s=we(n,a);return s?{...n,[s]:n[s].map(i=>i.id==a?{...i,requestClose:!0}:i)}:n})},isActive:a=>!!re(C.getState(),a).position}}var se=0;function xt(e,t={}){var r,o;se+=1;const a=(r=t.id)!=null?r:se,n=(o=t.position)!=null?o:"bottom";return{id:a,message:e,position:n,duration:t.duration,onCloseComplete:t.onCloseComplete,onRequestRemove:()=>C.removeToast(String(a),n),status:t.status,requestClose:!1,containerStyle:t.containerStyle}}var _t=e=>{const{status:t,variant:r="solid",id:o,title:a,isClosable:n,onClose:s,description:i,colorScheme:l,icon:c}=e,u=o?{root:`toast-${o}`,title:`toast-${o}-title`,description:`toast-${o}-description`}:void 0;return d.jsxs($e,{addRole:!1,status:t,variant:r,id:u==null?void 0:u.root,alignItems:"start",borderRadius:"md",boxShadow:"lg",paddingEnd:8,textAlign:"start",width:"auto",colorScheme:l,children:[d.jsx(Ae,{children:c}),d.jsxs(E.div,{flex:"1",maxWidth:"100%",children:[a&&d.jsx(Ne,{id:u==null?void 0:u.title,children:a}),i&&d.jsx(Ee,{id:u==null?void 0:u.description,display:"block",children:i})]}),n&&d.jsx(Te,{size:"sm",onClick:s,position:"absolute",insetEnd:1,top:1})]})};function Ie(e={}){const{render:t,toastComponent:r=_t}=e;return a=>typeof t=="function"?t({...a,...e}):d.jsx(r,{...a,...e})}function zr(e,t){const r=a=>{var n;return{...t,...a,position:dt((n=a==null?void 0:a.position)!=null?n:t==null?void 0:t.position,e)}},o=a=>{const n=r(a),s=Ie(n);return C.notify(s,n)};return o.update=(a,n)=>{C.update(a,r(n))},o.promise=(a,n)=>{const s=o({...n.loading,status:"loading",duration:null});a.then(i=>o.update(s,{status:"success",duration:5e3,...q(n.success,i)})).catch(i=>o.update(s,{status:"error",duration:5e3,...q(n.error,i)}))},o.closeAll=C.closeAll,o.close=C.close,o.isActive=C.isActive,o}var[Rr,Mr]=M({name:"ToastOptionsContext",strict:!1}),Lr=e=>{const t=p.useSyncExternalStore(C.subscribe,C.getState,C.getState),{motionVariants:r,component:o=Pe,portalProps:a}=e,s=Object.keys(t).map(i=>{const l=t[i];return d.jsx("div",{role:"region","aria-live":"polite",id:`chakra-toast-manager-${i}`,style:it(i),children:d.jsx(Ue,{initial:!1,children:l.map(c=>d.jsx(o,{motionVariants:r,...c},c.id))})},i)});return d.jsx(G,{...a,children:s})};function Ct(){if(console&&console.warn){for(var e=arguments.length,t=new Array(e),r=0;r()=>{if(e.isInitialized)t();else{const r=()=>{setTimeout(()=>{e.off("initialized",r)},0),t()};e.on("initialized",r)}};function le(e,t,r){e.loadNamespaces(t,Oe(e,r))}function ce(e,t,r,o){typeof r=="string"&&(r=[r]),r.forEach(a=>{e.options.ns.indexOf(a)<0&&e.options.ns.push(a)}),e.loadLanguages(t,Oe(e,o))}function kt(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const o=t.languages[0],a=t.options?t.options.fallbackLng:!1,n=t.languages[t.languages.length-1];if(o.toLowerCase()==="cimode")return!0;const s=(i,l)=>{const c=t.services.backendConnector.state[`${i}|${l}`];return c===-1||c===2};return r.bindI18n&&r.bindI18n.indexOf("languageChanging")>-1&&t.services.backendConnector.backend&&t.isLanguageChangingTo&&!s(t.isLanguageChangingTo,e)?!1:!!(t.hasResourceBundle(o,e)||!t.services.backendConnector.backend||t.options.resources&&!t.options.partialBundledLanguages||s(o,e)&&(!a||s(n,e)))}function wt(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return!t.languages||!t.languages.length?(X("i18n.languages were undefined or empty",t.languages),!0):t.options.ignoreJSONStructure!==void 0?t.hasLoadedNamespace(e,{lng:r.lng,precheck:(a,n)=>{if(r.bindI18n&&r.bindI18n.indexOf("languageChanging")>-1&&a.services.backendConnector.backend&&a.isLanguageChangingTo&&!n(a.isLanguageChangingTo,e))return!1}}):kt(e,t,r)}const Pt=p.createContext();class jt{constructor(){this.usedNamespaces={}}addUsedNamespaces(t){t.forEach(r=>{this.usedNamespaces[r]||(this.usedNamespaces[r]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}const Et=(e,t)=>{const r=p.useRef();return p.useEffect(()=>{r.current=t?r.current:e},[e,t]),r.current};function Fr(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const{i18n:r}=t,{i18n:o,defaultNS:a}=p.useContext(Pt)||{},n=r||o||Ze();if(n&&!n.reportNamespaces&&(n.reportNamespaces=new jt),!n){X("You will need to pass in an i18next instance by using initReactI18next");const h=(w,x)=>typeof x=="string"?x:x&&typeof x=="object"&&typeof x.defaultValue=="string"?x.defaultValue:Array.isArray(w)?w[w.length-1]:w,k=[h,{},!1];return k.t=h,k.i18n={},k.ready=!1,k}n.options.react&&n.options.react.wait!==void 0&&X("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");const s={...Ve(),...n.options.react,...t},{useSuspense:i,keyPrefix:l}=s;let c=e||a||n.options&&n.options.defaultNS;c=typeof c=="string"?[c]:c||["translation"],n.reportNamespaces.addUsedNamespaces&&n.reportNamespaces.addUsedNamespaces(c);const u=(n.isInitialized||n.initializedStoreOnce)&&c.every(h=>wt(h,n,s));function f(){return n.getFixedT(t.lng||null,s.nsMode==="fallback"?c:c[0],l)}const[y,g]=p.useState(f);let v=c.join();t.lng&&(v=`${t.lng}${v}`);const $=Et(v),S=p.useRef(!0);p.useEffect(()=>{const{bindI18n:h,bindI18nStore:k}=s;S.current=!0,!u&&!i&&(t.lng?ce(n,t.lng,c,()=>{S.current&&g(f)}):le(n,c,()=>{S.current&&g(f)})),u&&$&&$!==v&&S.current&&g(f);function w(){S.current&&g(f)}return h&&n&&n.on(h,w),k&&n&&n.store.on(k,w),()=>{S.current=!1,h&&n&&h.split(" ").forEach(x=>n.off(x,w)),k&&n&&k.split(" ").forEach(x=>n.store.off(x,w))}},[n,v]);const H=p.useRef(!0);p.useEffect(()=>{S.current&&!H.current&&g(f),H.current=!1},[n,l]);const N=[y,n,u];if(N.t=y,N.i18n=n,N.ready=u,u||!u&&!i)return N;throw new Promise(h=>{t.lng?ce(n,t.lng,c,()=>h()):le(n,c,()=>h())})}function m(e,t={}){let r=!1;function o(){if(!r){r=!0;return}throw new Error("[anatomy] .part(...) should only be called once. Did you mean to use .extend(...) ?")}function a(...u){o();for(const f of u)t[f]=l(f);return m(e,t)}function n(...u){for(const f of u)f in t||(t[f]=l(f));return m(e,t)}function s(){return Object.fromEntries(Object.entries(t).map(([f,y])=>[f,y.selector]))}function i(){return Object.fromEntries(Object.entries(t).map(([f,y])=>[f,y.className]))}function l(u){const g=`chakra-${(["container","root"].includes(u??"")?[e]:[e,u]).filter(Boolean).join("__")}`;return{className:g,selector:`.${g}`,toString:()=>u}}return{parts:a,toPart:l,extend:n,selectors:s,classnames:i,get keys(){return Object.keys(t)},__type:{}}}var Hr=m("accordion").parts("root","container","button","panel").extend("icon");m("alert").parts("title","description","container").extend("icon","spinner");m("avatar").parts("label","badge","container").extend("excessLabel","group");m("breadcrumb").parts("link","item","container").extend("separator");m("button").parts();var Wr=m("checkbox").parts("control","icon","container").extend("label");m("progress").parts("track","filledTrack").extend("label");m("drawer").parts("overlay","dialogContainer","dialog").extend("header","closeButton","body","footer");var Dr=m("editable").parts("preview","input","textarea");m("form").parts("container","requiredIndicator","helperText");m("formError").parts("text","icon");var Br=m("input").parts("addon","field","element");m("list").parts("container","item","icon");var At=m("menu").parts("button","list","item").extend("groupTitle","command","divider"),Gr=m("modal").parts("overlay","dialogContainer","dialog").extend("header","closeButton","body","footer"),Ur=m("numberinput").parts("root","field","stepperGroup","stepper");m("pininput").parts("field");var Vr=m("popover").parts("content","header","body","footer").extend("popper","arrow","closeButton"),Zr=m("progress").parts("label","filledTrack","track");m("radio").parts("container","control","label");var qr=m("select").parts("field","icon"),Xr=m("slider").parts("container","track","thumb","filledTrack","mark");m("stat").parts("container","label","helpText","number","icon");var Yr=m("switch").parts("container","track","thumb");m("table").parts("table","thead","tbody","tr","th","td","tfoot","caption");var Jr=m("tabs").parts("root","tab","tablist","tabpanel","tabpanels","indicator");m("tag").parts("container","label","closeButton");m("card").parts("container","header","body","footer");const{definePartsStyle:Nt,defineMultiStyleConfig:$t}=qe(At.keys),Tt=Nt(e=>({button:{fontWeight:500,bg:P("base.300","base.500")(e),color:P("base.900","base.100")(e),_hover:{bg:P("base.400","base.600")(e),color:P("base.900","base.50")(e),fontWeight:600}},list:{zIndex:9999,color:P("base.900","base.150")(e),bg:P("base.200","base.800")(e),shadow:"dark-lg",border:"none"},item:{fontSize:"sm",bg:P("base.200","base.800")(e),_hover:{bg:P("base.300","base.700")(e),svg:{opacity:1}},_focus:{bg:P("base.400","base.600")(e)},svg:{opacity:.7,fontSize:14}}})),Kr=$t({variants:{invokeAI:Tt},defaultProps:{variant:"invokeAI"}}),Qr={variants:{enter:{visibility:"visible",opacity:1,scale:1,transition:{duration:.07,ease:[.4,0,.2,1]}},exit:{transitionEnd:{visibility:"hidden"},opacity:0,scale:.8,transition:{duration:.07,easings:"easeOut"}}}},It={dark:["#C1C2C5","#A6A7AB","#909296","#5c5f66","#373A40","#2C2E33","#25262b","#1A1B1E","#141517","#101113"],gray:["#f8f9fa","#f1f3f5","#e9ecef","#dee2e6","#ced4da","#adb5bd","#868e96","#495057","#343a40","#212529"],red:["#fff5f5","#ffe3e3","#ffc9c9","#ffa8a8","#ff8787","#ff6b6b","#fa5252","#f03e3e","#e03131","#c92a2a"],pink:["#fff0f6","#ffdeeb","#fcc2d7","#faa2c1","#f783ac","#f06595","#e64980","#d6336c","#c2255c","#a61e4d"],grape:["#f8f0fc","#f3d9fa","#eebefa","#e599f7","#da77f2","#cc5de8","#be4bdb","#ae3ec9","#9c36b5","#862e9c"],violet:["#f3f0ff","#e5dbff","#d0bfff","#b197fc","#9775fa","#845ef7","#7950f2","#7048e8","#6741d9","#5f3dc4"],indigo:["#edf2ff","#dbe4ff","#bac8ff","#91a7ff","#748ffc","#5c7cfa","#4c6ef5","#4263eb","#3b5bdb","#364fc7"],blue:["#e7f5ff","#d0ebff","#a5d8ff","#74c0fc","#4dabf7","#339af0","#228be6","#1c7ed6","#1971c2","#1864ab"],cyan:["#e3fafc","#c5f6fa","#99e9f2","#66d9e8","#3bc9db","#22b8cf","#15aabf","#1098ad","#0c8599","#0b7285"],teal:["#e6fcf5","#c3fae8","#96f2d7","#63e6be","#38d9a9","#20c997","#12b886","#0ca678","#099268","#087f5b"],green:["#ebfbee","#d3f9d8","#b2f2bb","#8ce99a","#69db7c","#51cf66","#40c057","#37b24d","#2f9e44","#2b8a3e"],lime:["#f4fce3","#e9fac8","#d8f5a2","#c0eb75","#a9e34b","#94d82d","#82c91e","#74b816","#66a80f","#5c940d"],yellow:["#fff9db","#fff3bf","#ffec99","#ffe066","#ffd43b","#fcc419","#fab005","#f59f00","#f08c00","#e67700"],orange:["#fff4e6","#ffe8cc","#ffd8a8","#ffc078","#ffa94d","#ff922b","#fd7e14","#f76707","#e8590c","#d9480f"]};function Ot(e){return()=>({fontFamily:e.fontFamily||"sans-serif"})}var zt=Object.defineProperty,ue=Object.getOwnPropertySymbols,Rt=Object.prototype.hasOwnProperty,Mt=Object.prototype.propertyIsEnumerable,de=(e,t,r)=>t in e?zt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,fe=(e,t)=>{for(var r in t||(t={}))Rt.call(t,r)&&de(e,r,t[r]);if(ue)for(var r of ue(t))Mt.call(t,r)&&de(e,r,t[r]);return e};function Lt(e){return t=>({WebkitTapHighlightColor:"transparent",[t||"&:focus"]:fe({},e.focusRing==="always"||e.focusRing==="auto"?e.focusRingStyles.styles(e):e.focusRingStyles.resetStyles(e)),[t?t.replace(":focus",":focus:not(:focus-visible)"):"&:focus:not(:focus-visible)"]:fe({},e.focusRing==="auto"||e.focusRing==="never"?e.focusRingStyles.resetStyles(e):null)})}function F(e){return t=>typeof e.primaryShade=="number"?e.primaryShade:e.primaryShade[t||e.colorScheme]}function Q(e){const t=F(e);return(r,o,a=!0,n=!0)=>{if(typeof r=="string"&&r.includes(".")){const[i,l]=r.split("."),c=parseInt(l,10);if(i in e.colors&&c>=0&&c<10)return e.colors[i][typeof o=="number"&&!n?o:c]}const s=typeof o=="number"?o:t();return r in e.colors?e.colors[r][s]:a?e.colors[e.primaryColor][s]:r}}function ze(e){let t="";for(let r=1;r{const a={from:(o==null?void 0:o.from)||e.defaultGradient.from,to:(o==null?void 0:o.to)||e.defaultGradient.to,deg:(o==null?void 0:o.deg)||e.defaultGradient.deg};return`linear-gradient(${a.deg}deg, ${t(a.from,r(),!1)} 0%, ${t(a.to,r(),!1)} 100%)`}}function Me(e){return t=>{if(typeof t=="number")return`${t/16}${e}`;if(typeof t=="string"){const r=t.replace("px","");if(!Number.isNaN(Number(r)))return`${Number(r)/16}${e}`}return t}}const A=Me("rem"),U=Me("em");function Le({size:e,sizes:t,units:r}){return e in t?t[e]:typeof e=="number"?r==="em"?U(e):A(e):e||t.md}function W(e){return typeof e=="number"?e:typeof e=="string"&&e.includes("rem")?Number(e.replace("rem",""))*16:typeof e=="string"&&e.includes("em")?Number(e.replace("em",""))*16:Number(e)}function Wt(e){return t=>`@media (min-width: ${U(W(Le({size:t,sizes:e.breakpoints})))})`}function Dt(e){return t=>`@media (max-width: ${U(W(Le({size:t,sizes:e.breakpoints}))-1)})`}function Bt(e){return/^#?([0-9A-F]{3}){1,2}$/i.test(e)}function Gt(e){let t=e.replace("#","");if(t.length===3){const s=t.split("");t=[s[0],s[0],s[1],s[1],s[2],s[2]].join("")}const r=parseInt(t,16),o=r>>16&255,a=r>>8&255,n=r&255;return{r:o,g:a,b:n,a:1}}function Ut(e){const[t,r,o,a]=e.replace(/[^0-9,.]/g,"").split(",").map(Number);return{r:t,g:r,b:o,a:a||1}}function ee(e){return Bt(e)?Gt(e):e.startsWith("rgb")?Ut(e):{r:0,g:0,b:0,a:1}}function T(e,t){if(typeof e!="string"||t>1||t<0)return"rgba(0, 0, 0, 1)";if(e.startsWith("var(--"))return e;const{r,g:o,b:a}=ee(e);return`rgba(${r}, ${o}, ${a}, ${t})`}function Vt(e=0){return{position:"absolute",top:A(e),right:A(e),left:A(e),bottom:A(e)}}function Zt(e,t){if(typeof e=="string"&&e.startsWith("var(--"))return e;const{r,g:o,b:a,a:n}=ee(e),s=1-t,i=l=>Math.round(l*s);return`rgba(${i(r)}, ${i(o)}, ${i(a)}, ${n})`}function qt(e,t){if(typeof e=="string"&&e.startsWith("var(--"))return e;const{r,g:o,b:a,a:n}=ee(e),s=i=>Math.round(i+(255-i)*t);return`rgba(${s(r)}, ${s(o)}, ${s(a)}, ${n})`}function Xt(e){return t=>{if(typeof t=="number")return A(t);const r=typeof e.defaultRadius=="number"?e.defaultRadius:e.radius[e.defaultRadius]||e.defaultRadius;return e.radius[t]||t||r}}function Yt(e,t){if(typeof e=="string"&&e.includes(".")){const[r,o]=e.split("."),a=parseInt(o,10);if(r in t.colors&&a>=0&&a<10)return{isSplittedColor:!0,key:r,shade:a}}return{isSplittedColor:!1}}function Jt(e){const t=Q(e),r=F(e),o=Re(e);return({variant:a,color:n,gradient:s,primaryFallback:i})=>{const l=Yt(n,e);switch(a){case"light":return{border:"transparent",background:T(t(n,e.colorScheme==="dark"?8:0,i,!1),e.colorScheme==="dark"?.2:1),color:n==="dark"?e.colorScheme==="dark"?e.colors.dark[0]:e.colors.dark[9]:t(n,e.colorScheme==="dark"?2:r("light")),hover:T(t(n,e.colorScheme==="dark"?7:1,i,!1),e.colorScheme==="dark"?.25:.65)};case"subtle":return{border:"transparent",background:"transparent",color:n==="dark"?e.colorScheme==="dark"?e.colors.dark[0]:e.colors.dark[9]:t(n,e.colorScheme==="dark"?2:r("light")),hover:T(t(n,e.colorScheme==="dark"?8:0,i,!1),e.colorScheme==="dark"?.2:1)};case"outline":return{border:t(n,e.colorScheme==="dark"?5:r("light")),background:"transparent",color:t(n,e.colorScheme==="dark"?5:r("light")),hover:e.colorScheme==="dark"?T(t(n,5,i,!1),.05):T(t(n,0,i,!1),.35)};case"default":return{border:e.colorScheme==="dark"?e.colors.dark[4]:e.colors.gray[4],background:e.colorScheme==="dark"?e.colors.dark[6]:e.white,color:e.colorScheme==="dark"?e.white:e.black,hover:e.colorScheme==="dark"?e.colors.dark[5]:e.colors.gray[0]};case"white":return{border:"transparent",background:e.white,color:t(n,r()),hover:null};case"transparent":return{border:"transparent",color:n==="dark"?e.colorScheme==="dark"?e.colors.dark[0]:e.colors.dark[9]:t(n,e.colorScheme==="dark"?2:r("light")),background:"transparent",hover:null};case"gradient":return{background:o(s),color:e.white,border:"transparent",hover:null};default:{const c=r(),u=l.isSplittedColor?l.shade:c,f=l.isSplittedColor?l.key:n;return{border:"transparent",background:t(f,u,i),color:e.white,hover:t(f,u===9?8:u+1)}}}}}function Kt(e){return t=>{const r=F(e)(t);return e.colors[e.primaryColor][r]}}function Qt(e){return{"@media (hover: hover)":{"&:hover":e},"@media (hover: none)":{"&:active":e}}}function er(e){return()=>({userSelect:"none",color:e.colorScheme==="dark"?e.colors.dark[3]:e.colors.gray[5]})}function tr(e){return()=>e.colorScheme==="dark"?e.colors.dark[2]:e.colors.gray[6]}const b={fontStyles:Ot,themeColor:Q,focusStyles:Lt,linearGradient:Ft,radialGradient:Ht,smallerThan:Dt,largerThan:Wt,rgba:T,cover:Vt,darken:Zt,lighten:qt,radius:Xt,variant:Jt,primaryShade:F,hover:Qt,gradient:Re,primaryColor:Kt,placeholderStyles:er,dimmed:tr};var rr=Object.defineProperty,nr=Object.defineProperties,or=Object.getOwnPropertyDescriptors,pe=Object.getOwnPropertySymbols,ar=Object.prototype.hasOwnProperty,sr=Object.prototype.propertyIsEnumerable,me=(e,t,r)=>t in e?rr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ir=(e,t)=>{for(var r in t||(t={}))ar.call(t,r)&&me(e,r,t[r]);if(pe)for(var r of pe(t))sr.call(t,r)&&me(e,r,t[r]);return e},lr=(e,t)=>nr(e,or(t));function Fe(e){return lr(ir({},e),{fn:{fontStyles:b.fontStyles(e),themeColor:b.themeColor(e),focusStyles:b.focusStyles(e),largerThan:b.largerThan(e),smallerThan:b.smallerThan(e),radialGradient:b.radialGradient,linearGradient:b.linearGradient,gradient:b.gradient(e),rgba:b.rgba,cover:b.cover,lighten:b.lighten,darken:b.darken,primaryShade:b.primaryShade(e),radius:b.radius(e),variant:b.variant(e),hover:b.hover,primaryColor:b.primaryColor(e),placeholderStyles:b.placeholderStyles(e),dimmed:b.dimmed(e)}})}const cr={dir:"ltr",primaryShade:{light:6,dark:8},focusRing:"auto",loader:"oval",colorScheme:"light",white:"#fff",black:"#000",defaultRadius:"sm",transitionTimingFunction:"ease",colors:It,lineHeight:1.55,fontFamily:"-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji",fontFamilyMonospace:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, Liberation Mono, Courier New, monospace",primaryColor:"blue",respectReducedMotion:!0,cursorType:"default",defaultGradient:{from:"indigo",to:"cyan",deg:45},shadows:{xs:"0 0.0625rem 0.1875rem rgba(0, 0, 0, 0.05), 0 0.0625rem 0.125rem rgba(0, 0, 0, 0.1)",sm:"0 0.0625rem 0.1875rem rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0.05) 0 0.625rem 0.9375rem -0.3125rem, rgba(0, 0, 0, 0.04) 0 0.4375rem 0.4375rem -0.3125rem",md:"0 0.0625rem 0.1875rem rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0.05) 0 1.25rem 1.5625rem -0.3125rem, rgba(0, 0, 0, 0.04) 0 0.625rem 0.625rem -0.3125rem",lg:"0 0.0625rem 0.1875rem rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0.05) 0 1.75rem 1.4375rem -0.4375rem, rgba(0, 0, 0, 0.04) 0 0.75rem 0.75rem -0.4375rem",xl:"0 0.0625rem 0.1875rem rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0.05) 0 2.25rem 1.75rem -0.4375rem, rgba(0, 0, 0, 0.04) 0 1.0625rem 1.0625rem -0.4375rem"},fontSizes:{xs:"0.75rem",sm:"0.875rem",md:"1rem",lg:"1.125rem",xl:"1.25rem"},radius:{xs:"0.125rem",sm:"0.25rem",md:"0.5rem",lg:"1rem",xl:"2rem"},spacing:{xs:"0.625rem",sm:"0.75rem",md:"1rem",lg:"1.25rem",xl:"1.5rem"},breakpoints:{xs:"36em",sm:"48em",md:"62em",lg:"75em",xl:"88em"},headings:{fontFamily:"-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji",fontWeight:700,sizes:{h1:{fontSize:"2.125rem",lineHeight:1.3,fontWeight:void 0},h2:{fontSize:"1.625rem",lineHeight:1.35,fontWeight:void 0},h3:{fontSize:"1.375rem",lineHeight:1.4,fontWeight:void 0},h4:{fontSize:"1.125rem",lineHeight:1.45,fontWeight:void 0},h5:{fontSize:"1rem",lineHeight:1.5,fontWeight:void 0},h6:{fontSize:"0.875rem",lineHeight:1.5,fontWeight:void 0}}},other:{},components:{},activeStyles:{transform:"translateY(0.0625rem)"},datesLocale:"en",globalStyles:void 0,focusRingStyles:{styles:e=>({outlineOffset:"0.125rem",outline:`0.125rem solid ${e.colors[e.primaryColor][e.colorScheme==="dark"?7:5]}`}),resetStyles:()=>({outline:"none"}),inputStyles:e=>({outline:"none",borderColor:e.colors[e.primaryColor][typeof e.primaryShade=="object"?e.primaryShade[e.colorScheme]:e.primaryShade]})}},te=Fe(cr);var ur=Object.defineProperty,dr=Object.defineProperties,fr=Object.getOwnPropertyDescriptors,ge=Object.getOwnPropertySymbols,pr=Object.prototype.hasOwnProperty,mr=Object.prototype.propertyIsEnumerable,be=(e,t,r)=>t in e?ur(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,gr=(e,t)=>{for(var r in t||(t={}))pr.call(t,r)&&be(e,r,t[r]);if(ge)for(var r of ge(t))mr.call(t,r)&&be(e,r,t[r]);return e},br=(e,t)=>dr(e,fr(t));function yr({theme:e}){return j.createElement(B,{styles:{"*, *::before, *::after":{boxSizing:"border-box"},html:{colorScheme:e.colorScheme==="dark"?"dark":"light"},body:br(gr({},e.fn.fontStyles()),{backgroundColor:e.colorScheme==="dark"?e.colors.dark[7]:e.white,color:e.colorScheme==="dark"?e.colors.dark[0]:e.black,lineHeight:e.lineHeight,fontSize:e.fontSizes.md,WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"})}})}function I(e,t,r,o=A){Object.keys(t).forEach(a=>{e[`--mantine-${r}-${a}`]=o(t[a])})}function hr({theme:e}){const t={"--mantine-color-white":e.white,"--mantine-color-black":e.black,"--mantine-transition-timing-function":e.transitionTimingFunction,"--mantine-line-height":`${e.lineHeight}`,"--mantine-font-family":e.fontFamily,"--mantine-font-family-monospace":e.fontFamilyMonospace,"--mantine-font-family-headings":e.headings.fontFamily,"--mantine-heading-font-weight":`${e.headings.fontWeight}`};I(t,e.shadows,"shadow"),I(t,e.fontSizes,"font-size"),I(t,e.radius,"radius"),I(t,e.spacing,"spacing"),I(t,e.breakpoints,"breakpoints",U),Object.keys(e.colors).forEach(o=>{e.colors[o].forEach((a,n)=>{t[`--mantine-color-${o}-${n}`]=a})});const r=e.headings.sizes;return Object.keys(r).forEach(o=>{t[`--mantine-${o}-font-size`]=r[o].fontSize,t[`--mantine-${o}-line-height`]=`${r[o].lineHeight}`}),j.createElement(B,{styles:{":root":t}})}var vr=Object.defineProperty,Sr=Object.defineProperties,xr=Object.getOwnPropertyDescriptors,ye=Object.getOwnPropertySymbols,_r=Object.prototype.hasOwnProperty,Cr=Object.prototype.propertyIsEnumerable,he=(e,t,r)=>t in e?vr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,_=(e,t)=>{for(var r in t||(t={}))_r.call(t,r)&&he(e,r,t[r]);if(ye)for(var r of ye(t))Cr.call(t,r)&&he(e,r,t[r]);return e},V=(e,t)=>Sr(e,xr(t));function kr(e,t){var r;if(!t)return e;const o=Object.keys(e).reduce((a,n)=>{if(n==="headings"&&t.headings){const s=t.headings.sizes?Object.keys(e.headings.sizes).reduce((i,l)=>(i[l]=_(_({},e.headings.sizes[l]),t.headings.sizes[l]),i),{}):e.headings.sizes;return V(_({},a),{headings:V(_(_({},e.headings),t.headings),{sizes:s})})}if(n==="breakpoints"&&t.breakpoints){const s=_(_({},e.breakpoints),t.breakpoints);return V(_({},a),{breakpoints:Object.fromEntries(Object.entries(s).sort((i,l)=>W(i[1])-W(l[1])))})}return a[n]=typeof t[n]=="object"?_(_({},e[n]),t[n]):typeof t[n]=="number"||typeof t[n]=="boolean"||typeof t[n]=="function"?t[n]:t[n]||e[n],a},{});if(t!=null&&t.fontFamily&&!((r=t==null?void 0:t.headings)!=null&&r.fontFamily)&&(o.headings.fontFamily=t.fontFamily),!(o.primaryColor in o.colors))throw new Error("MantineProvider: Invalid theme.primaryColor, it accepts only key of theme.colors, learn more – https://mantine.dev/theming/colors/#primary-color");return o}function wr(e,t){return Fe(kr(e,t))}function Pr(e){return Object.keys(e).reduce((t,r)=>(e[r]!==void 0&&(t[r]=e[r]),t),{})}const jr={html:{fontFamily:"sans-serif",lineHeight:"1.15",textSizeAdjust:"100%"},body:{margin:0},"article, aside, footer, header, nav, section, figcaption, figure, main":{display:"block"},h1:{fontSize:"2em"},hr:{boxSizing:"content-box",height:0,overflow:"visible"},pre:{fontFamily:"monospace, monospace",fontSize:"1em"},a:{background:"transparent",textDecorationSkip:"objects"},"a:active, a:hover":{outlineWidth:0},"abbr[title]":{borderBottom:"none",textDecoration:"underline"},"b, strong":{fontWeight:"bolder"},"code, kbp, samp":{fontFamily:"monospace, monospace",fontSize:"1em"},dfn:{fontStyle:"italic"},mark:{backgroundColor:"#ff0",color:"#000"},small:{fontSize:"80%"},"sub, sup":{fontSize:"75%",lineHeight:0,position:"relative",verticalAlign:"baseline"},sup:{top:"-0.5em"},sub:{bottom:"-0.25em"},"audio, video":{display:"inline-block"},"audio:not([controls])":{display:"none",height:0},img:{borderStyle:"none",verticalAlign:"middle"},"svg:not(:root)":{overflow:"hidden"},"button, input, optgroup, select, textarea":{fontFamily:"sans-serif",fontSize:"100%",lineHeight:"1.15",margin:0},"button, input":{overflow:"visible"},"button, select":{textTransform:"none"},"button, [type=reset], [type=submit]":{WebkitAppearance:"button"},"button::-moz-focus-inner, [type=button]::-moz-focus-inner, [type=reset]::-moz-focus-inner, [type=submit]::-moz-focus-inner":{borderStyle:"none",padding:0},"button:-moz-focusring, [type=button]:-moz-focusring, [type=reset]:-moz-focusring, [type=submit]:-moz-focusring":{outline:`${A(1)} dotted ButtonText`},legend:{boxSizing:"border-box",color:"inherit",display:"table",maxWidth:"100%",padding:0,whiteSpace:"normal"},progress:{display:"inline-block",verticalAlign:"baseline"},textarea:{overflow:"auto"},"[type=checkbox], [type=radio]":{boxSizing:"border-box",padding:0},"[type=number]::-webkit-inner-spin-button, [type=number]::-webkit-outer-spin-button":{height:"auto"},"[type=search]":{appearance:"none"},"[type=search]::-webkit-search-cancel-button, [type=search]::-webkit-search-decoration":{appearance:"none"},"::-webkit-file-upload-button":{appearance:"button",font:"inherit"},"details, menu":{display:"block"},summary:{display:"list-item"},canvas:{display:"inline-block"},template:{display:"none"}};function Er(){return j.createElement(B,{styles:jr})}var Ar=Object.defineProperty,ve=Object.getOwnPropertySymbols,Nr=Object.prototype.hasOwnProperty,$r=Object.prototype.propertyIsEnumerable,Se=(e,t,r)=>t in e?Ar(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,O=(e,t)=>{for(var r in t||(t={}))Nr.call(t,r)&&Se(e,r,t[r]);if(ve)for(var r of ve(t))$r.call(t,r)&&Se(e,r,t[r]);return e};const D=p.createContext({theme:te});function He(){var e;return((e=p.useContext(D))==null?void 0:e.theme)||te}function en(e){const t=He(),r=o=>{var a,n,s,i;return{styles:((a=t.components[o])==null?void 0:a.styles)||{},classNames:((n=t.components[o])==null?void 0:n.classNames)||{},variants:(s=t.components[o])==null?void 0:s.variants,sizes:(i=t.components[o])==null?void 0:i.sizes}};return Array.isArray(e)?e.map(r):[r(e)]}function tn(){var e;return(e=p.useContext(D))==null?void 0:e.emotionCache}function rn(e,t,r){var o;const a=He(),n=(o=a.components[e])==null?void 0:o.defaultProps,s=typeof n=="function"?n(a):n;return O(O(O({},t),s),Pr(r))}function Tr({theme:e,emotionCache:t,withNormalizeCSS:r=!1,withGlobalStyles:o=!1,withCSSVariables:a=!1,inherit:n=!1,children:s}){const i=p.useContext(D),l=wr(te,n?O(O({},i.theme),e):e);return j.createElement(Xe,{theme:l},j.createElement(D.Provider,{value:{theme:l,emotionCache:t}},r&&j.createElement(Er,null),o&&j.createElement(yr,{theme:l}),a&&j.createElement(hr,{theme:l}),typeof l.globalStyles=="function"&&j.createElement(B,{styles:l.globalStyles(l)}),s))}Tr.displayName="@mantine/core/MantineProvider";export{Zr as A,qr as B,Te as C,Xr as D,Yr as E,Jr as F,Kr as G,L as I,Tr as M,G as P,Rr as T,M as a,lt as b,zr as c,ne as d,Fr as e,tn as f,He as g,en as h,Pr as i,W as j,Le as k,rn as l,Qr as m,P as n,Or as o,Qe as p,Lr as q,A as r,Hr as s,Wr as t,Mr as u,Dr as v,Br as w,Gr as x,Ur as y,Vr as z}; diff --git a/invokeai/frontend/web/dist/assets/ThemeLocaleProvider-9ac72450.js b/invokeai/frontend/web/dist/assets/ThemeLocaleProvider-9ac72450.js new file mode 100644 index 0000000000..83a0fe8451 --- /dev/null +++ b/invokeai/frontend/web/dist/assets/ThemeLocaleProvider-9ac72450.js @@ -0,0 +1,302 @@ +import{A as g,fS as Xe,z as x,a4 as Ba,fT as Ea,af as ca,aj as c,fU as b,al as Da,fV as t,fW as Ra,fX as h,fY as ba,fZ as ja,f_ as Ha,aI as Wa,f$ as Va,ad as La,g0 as qa}from"./index-89941396.js";import{n,o as Sr,p as Oa,T as Na,q as Ga,s as Ua,t as Ya,v as Xa,w as Ka,x as Za,y as Ja,z as Qa,A as et,B as rt,D as at,E as tt,F as ot,G as nt,e as it,M as lt}from"./MantineProvider-8184f020.js";var va=String.raw,ua=va` + :root, + :host { + --chakra-vh: 100vh; + } + + @supports (height: -webkit-fill-available) { + :root, + :host { + --chakra-vh: -webkit-fill-available; + } + } + + @supports (height: -moz-fill-available) { + :root, + :host { + --chakra-vh: -moz-fill-available; + } + } + + @supports (height: 100dvh) { + :root, + :host { + --chakra-vh: 100dvh; + } + } +`,st=()=>g.jsx(Xe,{styles:ua}),dt=({scope:e=""})=>g.jsx(Xe,{styles:va` + html { + line-height: 1.5; + -webkit-text-size-adjust: 100%; + font-family: system-ui, sans-serif; + -webkit-font-smoothing: antialiased; + text-rendering: optimizeLegibility; + -moz-osx-font-smoothing: grayscale; + touch-action: manipulation; + } + + body { + position: relative; + min-height: 100%; + margin: 0; + font-feature-settings: "kern"; + } + + ${e} :where(*, *::before, *::after) { + border-width: 0; + border-style: solid; + box-sizing: border-box; + word-wrap: break-word; + } + + main { + display: block; + } + + ${e} hr { + border-top-width: 1px; + box-sizing: content-box; + height: 0; + overflow: visible; + } + + ${e} :where(pre, code, kbd,samp) { + font-family: SFMono-Regular, Menlo, Monaco, Consolas, monospace; + font-size: 1em; + } + + ${e} a { + background-color: transparent; + color: inherit; + text-decoration: inherit; + } + + ${e} abbr[title] { + border-bottom: none; + text-decoration: underline; + -webkit-text-decoration: underline dotted; + text-decoration: underline dotted; + } + + ${e} :where(b, strong) { + font-weight: bold; + } + + ${e} small { + font-size: 80%; + } + + ${e} :where(sub,sup) { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; + } + + ${e} sub { + bottom: -0.25em; + } + + ${e} sup { + top: -0.5em; + } + + ${e} img { + border-style: none; + } + + ${e} :where(button, input, optgroup, select, textarea) { + font-family: inherit; + font-size: 100%; + line-height: 1.15; + margin: 0; + } + + ${e} :where(button, input) { + overflow: visible; + } + + ${e} :where(button, select) { + text-transform: none; + } + + ${e} :where( + button::-moz-focus-inner, + [type="button"]::-moz-focus-inner, + [type="reset"]::-moz-focus-inner, + [type="submit"]::-moz-focus-inner + ) { + border-style: none; + padding: 0; + } + + ${e} fieldset { + padding: 0.35em 0.75em 0.625em; + } + + ${e} legend { + box-sizing: border-box; + color: inherit; + display: table; + max-width: 100%; + padding: 0; + white-space: normal; + } + + ${e} progress { + vertical-align: baseline; + } + + ${e} textarea { + overflow: auto; + } + + ${e} :where([type="checkbox"], [type="radio"]) { + box-sizing: border-box; + padding: 0; + } + + ${e} input[type="number"]::-webkit-inner-spin-button, + ${e} input[type="number"]::-webkit-outer-spin-button { + -webkit-appearance: none !important; + } + + ${e} input[type="number"] { + -moz-appearance: textfield; + } + + ${e} input[type="search"] { + -webkit-appearance: textfield; + outline-offset: -2px; + } + + ${e} input[type="search"]::-webkit-search-decoration { + -webkit-appearance: none !important; + } + + ${e} ::-webkit-file-upload-button { + -webkit-appearance: button; + font: inherit; + } + + ${e} details { + display: block; + } + + ${e} summary { + display: list-item; + } + + template { + display: none; + } + + [hidden] { + display: none !important; + } + + ${e} :where( + blockquote, + dl, + dd, + h1, + h2, + h3, + h4, + h5, + h6, + hr, + figure, + p, + pre + ) { + margin: 0; + } + + ${e} button { + background: transparent; + padding: 0; + } + + ${e} fieldset { + margin: 0; + padding: 0; + } + + ${e} :where(ol, ul) { + margin: 0; + padding: 0; + } + + ${e} textarea { + resize: vertical; + } + + ${e} :where(button, [role="button"]) { + cursor: pointer; + } + + ${e} button::-moz-focus-inner { + border: 0 !important; + } + + ${e} table { + border-collapse: collapse; + } + + ${e} :where(h1, h2, h3, h4, h5, h6) { + font-size: inherit; + font-weight: inherit; + } + + ${e} :where(button, input, optgroup, select, textarea) { + padding: 0; + line-height: inherit; + color: inherit; + } + + ${e} :where(img, svg, video, canvas, audio, iframe, embed, object) { + display: block; + } + + ${e} :where(img, video) { + max-width: 100%; + height: auto; + } + + [data-js-focus-visible] + :focus:not([data-focus-visible-added]):not( + [data-focus-visible-disabled] + ) { + outline: none; + box-shadow: none; + } + + ${e} select::-ms-expand { + display: none; + } + + ${ua} + `}),_e={light:"chakra-ui-light",dark:"chakra-ui-dark"};function ct(e={}){const{preventTransition:r=!0}=e,a={setDataset:o=>{const i=r?a.preventTransition():void 0;document.documentElement.dataset.theme=o,document.documentElement.style.colorScheme=o,i==null||i()},setClassName(o){document.body.classList.add(o?_e.dark:_e.light),document.body.classList.remove(o?_e.light:_e.dark)},query(){return window.matchMedia("(prefers-color-scheme: dark)")},getSystemTheme(o){var i;return((i=a.query().matches)!=null?i:o==="dark")?"dark":"light"},addListener(o){const i=a.query(),l=s=>{o(s.matches?"dark":"light")};return typeof i.addListener=="function"?i.addListener(l):i.addEventListener("change",l),()=>{typeof i.removeListener=="function"?i.removeListener(l):i.removeEventListener("change",l)}},preventTransition(){const o=document.createElement("style");return o.appendChild(document.createTextNode("*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),document.head.appendChild(o),()=>{window.getComputedStyle(document.body),requestAnimationFrame(()=>{requestAnimationFrame(()=>{document.head.removeChild(o)})})}}};return a}var bt="chakra-ui-color-mode";function fa(e){return{ssr:!1,type:"localStorage",get(r){if(!(globalThis!=null&&globalThis.document))return r;let a;try{a=localStorage.getItem(e)||r}catch{}return a||r},set(r){try{localStorage.setItem(e,r)}catch{}}}}var vt=fa(bt),Cr=()=>{};function Ar(e,r){return e.type==="cookie"&&e.ssr?e.get(r):r}function ma(e){const{value:r,children:a,options:{useSystemColorMode:o,initialColorMode:i,disableTransitionOnChange:l}={},colorModeManager:s=vt}=e,d=i==="dark"?"dark":"light",[v,$]=x.useState(()=>Ar(s,d)),[p,S]=x.useState(()=>Ar(s)),{getSystemTheme:T,setClassName:L,setDataset:Qe,addListener:wr}=x.useMemo(()=>ct({preventTransition:l}),[l]),$e=i==="system"&&!v?p:v,F=x.useCallback(te=>{const ke=te==="system"?T():te;$(ke),L(ke==="dark"),Qe(ke),s.set(ke)},[s,T,L,Qe]);Ba(()=>{i==="system"&&S(T())},[]),x.useEffect(()=>{const te=s.get();if(te){F(te);return}if(i==="system"){F("system");return}F(d)},[s,d,i,F]);const zr=x.useCallback(()=>{F($e==="dark"?"light":"dark")},[$e,F]);x.useEffect(()=>{if(o)return wr(F)},[o,wr,F]);const Ma=x.useMemo(()=>({colorMode:r??$e,toggleColorMode:r?Cr:zr,setColorMode:r?Cr:F,forced:r!==void 0}),[$e,zr,F,r]);return g.jsx(Ea.Provider,{value:Ma,children:a})}ma.displayName="ColorModeProvider";var ut=["borders","breakpoints","colors","components","config","direction","fonts","fontSizes","fontWeights","letterSpacings","lineHeights","radii","shadows","sizes","space","styles","transition","zIndices"];function ft(e){return ca(e)?ut.every(r=>Object.prototype.hasOwnProperty.call(e,r)):!1}var mt={common:"background-color, border-color, color, fill, stroke, opacity, box-shadow, transform",colors:"background-color, border-color, color, fill, stroke",dimensions:"width, height",position:"left, right, top, bottom",background:"background-color, background-image, background-position"},ht={"ease-in":"cubic-bezier(0.4, 0, 1, 1)","ease-out":"cubic-bezier(0, 0, 0.2, 1)","ease-in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},gt={"ultra-fast":"50ms",faster:"100ms",fast:"150ms",normal:"200ms",slow:"300ms",slower:"400ms","ultra-slow":"500ms"},yt={property:mt,easing:ht,duration:gt},pt=yt,St={hide:-1,auto:"auto",base:0,docked:10,dropdown:1e3,sticky:1100,banner:1200,overlay:1300,modal:1400,popover:1500,skipLink:1600,toast:1700,tooltip:1800},xt=St,$t={none:0,"1px":"1px solid","2px":"2px solid","4px":"4px solid","8px":"8px solid"},kt=$t,_t={base:"0em",sm:"30em",md:"48em",lg:"62em",xl:"80em","2xl":"96em"},wt=_t,zt={transparent:"transparent",current:"currentColor",black:"#000000",white:"#FFFFFF",whiteAlpha:{50:"rgba(255, 255, 255, 0.04)",100:"rgba(255, 255, 255, 0.06)",200:"rgba(255, 255, 255, 0.08)",300:"rgba(255, 255, 255, 0.16)",400:"rgba(255, 255, 255, 0.24)",500:"rgba(255, 255, 255, 0.36)",600:"rgba(255, 255, 255, 0.48)",700:"rgba(255, 255, 255, 0.64)",800:"rgba(255, 255, 255, 0.80)",900:"rgba(255, 255, 255, 0.92)"},blackAlpha:{50:"rgba(0, 0, 0, 0.04)",100:"rgba(0, 0, 0, 0.06)",200:"rgba(0, 0, 0, 0.08)",300:"rgba(0, 0, 0, 0.16)",400:"rgba(0, 0, 0, 0.24)",500:"rgba(0, 0, 0, 0.36)",600:"rgba(0, 0, 0, 0.48)",700:"rgba(0, 0, 0, 0.64)",800:"rgba(0, 0, 0, 0.80)",900:"rgba(0, 0, 0, 0.92)"},gray:{50:"#F7FAFC",100:"#EDF2F7",200:"#E2E8F0",300:"#CBD5E0",400:"#A0AEC0",500:"#718096",600:"#4A5568",700:"#2D3748",800:"#1A202C",900:"#171923"},red:{50:"#FFF5F5",100:"#FED7D7",200:"#FEB2B2",300:"#FC8181",400:"#F56565",500:"#E53E3E",600:"#C53030",700:"#9B2C2C",800:"#822727",900:"#63171B"},orange:{50:"#FFFAF0",100:"#FEEBC8",200:"#FBD38D",300:"#F6AD55",400:"#ED8936",500:"#DD6B20",600:"#C05621",700:"#9C4221",800:"#7B341E",900:"#652B19"},yellow:{50:"#FFFFF0",100:"#FEFCBF",200:"#FAF089",300:"#F6E05E",400:"#ECC94B",500:"#D69E2E",600:"#B7791F",700:"#975A16",800:"#744210",900:"#5F370E"},green:{50:"#F0FFF4",100:"#C6F6D5",200:"#9AE6B4",300:"#68D391",400:"#48BB78",500:"#38A169",600:"#2F855A",700:"#276749",800:"#22543D",900:"#1C4532"},teal:{50:"#E6FFFA",100:"#B2F5EA",200:"#81E6D9",300:"#4FD1C5",400:"#38B2AC",500:"#319795",600:"#2C7A7B",700:"#285E61",800:"#234E52",900:"#1D4044"},blue:{50:"#ebf8ff",100:"#bee3f8",200:"#90cdf4",300:"#63b3ed",400:"#4299e1",500:"#3182ce",600:"#2b6cb0",700:"#2c5282",800:"#2a4365",900:"#1A365D"},cyan:{50:"#EDFDFD",100:"#C4F1F9",200:"#9DECF9",300:"#76E4F7",400:"#0BC5EA",500:"#00B5D8",600:"#00A3C4",700:"#0987A0",800:"#086F83",900:"#065666"},purple:{50:"#FAF5FF",100:"#E9D8FD",200:"#D6BCFA",300:"#B794F4",400:"#9F7AEA",500:"#805AD5",600:"#6B46C1",700:"#553C9A",800:"#44337A",900:"#322659"},pink:{50:"#FFF5F7",100:"#FED7E2",200:"#FBB6CE",300:"#F687B3",400:"#ED64A6",500:"#D53F8C",600:"#B83280",700:"#97266D",800:"#702459",900:"#521B41"},linkedin:{50:"#E8F4F9",100:"#CFEDFB",200:"#9BDAF3",300:"#68C7EC",400:"#34B3E4",500:"#00A0DC",600:"#008CC9",700:"#0077B5",800:"#005E93",900:"#004471"},facebook:{50:"#E8F4F9",100:"#D9DEE9",200:"#B7C2DA",300:"#6482C0",400:"#4267B2",500:"#385898",600:"#314E89",700:"#29487D",800:"#223B67",900:"#1E355B"},messenger:{50:"#D0E6FF",100:"#B9DAFF",200:"#A2CDFF",300:"#7AB8FF",400:"#2E90FF",500:"#0078FF",600:"#0063D1",700:"#0052AC",800:"#003C7E",900:"#002C5C"},whatsapp:{50:"#dffeec",100:"#b9f5d0",200:"#90edb3",300:"#65e495",400:"#3cdd78",500:"#22c35e",600:"#179848",700:"#0c6c33",800:"#01421c",900:"#001803"},twitter:{50:"#E5F4FD",100:"#C8E9FB",200:"#A8DCFA",300:"#83CDF7",400:"#57BBF5",500:"#1DA1F2",600:"#1A94DA",700:"#1681BF",800:"#136B9E",900:"#0D4D71"},telegram:{50:"#E3F2F9",100:"#C5E4F3",200:"#A2D4EC",300:"#7AC1E4",400:"#47A9DA",500:"#0088CC",600:"#007AB8",700:"#006BA1",800:"#005885",900:"#003F5E"}},Ct=zt,At={none:"0",sm:"0.125rem",base:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},Pt=At,Tt={xs:"0 0 0 1px rgba(0, 0, 0, 0.05)",sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)",md:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",xl:"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)","2xl":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",outline:"0 0 0 3px rgba(66, 153, 225, 0.6)",inner:"inset 0 2px 4px 0 rgba(0,0,0,0.06)",none:"none","dark-lg":"rgba(0, 0, 0, 0.1) 0px 0px 0px 1px, rgba(0, 0, 0, 0.2) 0px 5px 10px, rgba(0, 0, 0, 0.4) 0px 15px 40px"},Ft=Tt,It={none:0,sm:"4px",base:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},Mt=It,Bt={letterSpacings:{tighter:"-0.05em",tight:"-0.025em",normal:"0",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeights:{normal:"normal",none:1,shorter:1.25,short:1.375,base:1.5,tall:1.625,taller:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},fontWeights:{hairline:100,thin:200,light:300,normal:400,medium:500,semibold:600,bold:700,extrabold:800,black:900},fonts:{heading:'-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',body:'-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',mono:'SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace'},fontSizes:{"3xs":"0.45rem","2xs":"0.625rem",xs:"0.75rem",sm:"0.875rem",md:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem","5xl":"3rem","6xl":"3.75rem","7xl":"4.5rem","8xl":"6rem","9xl":"8rem"}},ha=Bt,ga={px:"1px",.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},Et={max:"max-content",min:"min-content",full:"100%","3xs":"14rem","2xs":"16rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem","8xl":"90rem",prose:"60ch"},Dt={sm:"640px",md:"768px",lg:"1024px",xl:"1280px"},Rt={...ga,...Et,container:Dt},ya=Rt,jt={breakpoints:wt,zIndices:xt,radii:Pt,blur:Mt,colors:Ct,...ha,sizes:ya,shadows:Ft,space:ga,borders:kt,transition:pt},{defineMultiStyleConfig:Ht,definePartsStyle:le}=b(["stepper","step","title","description","indicator","separator","icon","number"]),B=c("stepper-indicator-size"),X=c("stepper-icon-size"),K=c("stepper-title-font-size"),se=c("stepper-description-font-size"),oe=c("stepper-accent-color"),Wt=le(({colorScheme:e})=>({stepper:{display:"flex",justifyContent:"space-between",gap:"4","&[data-orientation=vertical]":{flexDirection:"column",alignItems:"flex-start"},"&[data-orientation=horizontal]":{flexDirection:"row",alignItems:"center"},[oe.variable]:`colors.${e}.500`,_dark:{[oe.variable]:`colors.${e}.200`}},title:{fontSize:K.reference,fontWeight:"medium"},description:{fontSize:se.reference,color:"chakra-subtle-text"},number:{fontSize:K.reference},step:{flexShrink:0,position:"relative",display:"flex",gap:"2","&[data-orientation=horizontal]":{alignItems:"center"},flex:"1","&:last-of-type:not([data-stretch])":{flex:"initial"}},icon:{flexShrink:0,width:X.reference,height:X.reference},indicator:{flexShrink:0,borderRadius:"full",width:B.reference,height:B.reference,display:"flex",justifyContent:"center",alignItems:"center","&[data-status=active]":{borderWidth:"2px",borderColor:oe.reference},"&[data-status=complete]":{bg:oe.reference,color:"chakra-inverse-text"},"&[data-status=incomplete]":{borderWidth:"2px"}},separator:{bg:"chakra-border-color",flex:"1","&[data-status=complete]":{bg:oe.reference},"&[data-orientation=horizontal]":{width:"100%",height:"2px",marginStart:"2"},"&[data-orientation=vertical]":{width:"2px",position:"absolute",height:"100%",maxHeight:`calc(100% - ${B.reference} - 8px)`,top:`calc(${B.reference} + 4px)`,insetStart:`calc(${B.reference} / 2 - 1px)`}}})),Vt=Ht({baseStyle:Wt,sizes:{xs:le({stepper:{[B.variable]:"sizes.4",[X.variable]:"sizes.3",[K.variable]:"fontSizes.xs",[se.variable]:"fontSizes.xs"}}),sm:le({stepper:{[B.variable]:"sizes.6",[X.variable]:"sizes.4",[K.variable]:"fontSizes.sm",[se.variable]:"fontSizes.xs"}}),md:le({stepper:{[B.variable]:"sizes.8",[X.variable]:"sizes.5",[K.variable]:"fontSizes.md",[se.variable]:"fontSizes.sm"}}),lg:le({stepper:{[B.variable]:"sizes.10",[X.variable]:"sizes.6",[K.variable]:"fontSizes.lg",[se.variable]:"fontSizes.md"}})},defaultProps:{size:"md",colorScheme:"blue"}});function f(e,r={}){let a=!1;function o(){if(!a){a=!0;return}throw new Error("[anatomy] .part(...) should only be called once. Did you mean to use .extend(...) ?")}function i(...p){o();for(const S of p)r[S]=v(S);return f(e,r)}function l(...p){for(const S of p)S in r||(r[S]=v(S));return f(e,r)}function s(){return Object.fromEntries(Object.entries(r).map(([S,T])=>[S,T.selector]))}function d(){return Object.fromEntries(Object.entries(r).map(([S,T])=>[S,T.className]))}function v(p){const L=`chakra-${(["container","root"].includes(p??"")?[e]:[e,p]).filter(Boolean).join("__")}`;return{className:L,selector:`.${L}`,toString:()=>p}}return{parts:i,toPart:v,extend:l,selectors:s,classnames:d,get keys(){return Object.keys(r)},__type:{}}}var Lt=f("accordion").parts("root","container","button","panel").extend("icon"),qt=f("alert").parts("title","description","container").extend("icon","spinner"),Ot=f("avatar").parts("label","badge","container").extend("excessLabel","group"),Nt=f("breadcrumb").parts("link","item","container").extend("separator");f("button").parts();var Gt=f("checkbox").parts("control","icon","container").extend("label");f("progress").parts("track","filledTrack").extend("label");var Ut=f("drawer").parts("overlay","dialogContainer","dialog").extend("header","closeButton","body","footer"),Yt=f("editable").parts("preview","input","textarea"),Xt=f("form").parts("container","requiredIndicator","helperText"),Kt=f("formError").parts("text","icon"),Zt=f("input").parts("addon","field","element"),Jt=f("list").parts("container","item","icon"),Qt=f("menu").parts("button","list","item").extend("groupTitle","command","divider"),eo=f("modal").parts("overlay","dialogContainer","dialog").extend("header","closeButton","body","footer"),ro=f("numberinput").parts("root","field","stepperGroup","stepper");f("pininput").parts("field");var ao=f("popover").parts("content","header","body","footer").extend("popper","arrow","closeButton"),to=f("progress").parts("label","filledTrack","track"),oo=f("radio").parts("container","control","label"),no=f("select").parts("field","icon"),io=f("slider").parts("container","track","thumb","filledTrack","mark"),lo=f("stat").parts("container","label","helpText","number","icon"),so=f("switch").parts("container","track","thumb"),co=f("table").parts("table","thead","tbody","tr","th","td","tfoot","caption"),bo=f("tabs").parts("root","tab","tablist","tabpanel","tabpanels","indicator"),vo=f("tag").parts("container","label","closeButton"),uo=f("card").parts("container","header","body","footer");function O(e,r,a){return Math.min(Math.max(e,a),r)}class fo extends Error{constructor(r){super(`Failed to parse color: "${r}"`)}}var de=fo;function xr(e){if(typeof e!="string")throw new de(e);if(e.trim().toLowerCase()==="transparent")return[0,0,0,0];let r=e.trim();r=$o.test(e)?go(e):e;const a=yo.exec(r);if(a){const s=Array.from(a).slice(1);return[...s.slice(0,3).map(d=>parseInt(ge(d,2),16)),parseInt(ge(s[3]||"f",2),16)/255]}const o=po.exec(r);if(o){const s=Array.from(o).slice(1);return[...s.slice(0,3).map(d=>parseInt(d,16)),parseInt(s[3]||"ff",16)/255]}const i=So.exec(r);if(i){const s=Array.from(i).slice(1);return[...s.slice(0,3).map(d=>parseInt(d,10)),parseFloat(s[3]||"1")]}const l=xo.exec(r);if(l){const[s,d,v,$]=Array.from(l).slice(1).map(parseFloat);if(O(0,100,d)!==d)throw new de(e);if(O(0,100,v)!==v)throw new de(e);return[...ko(s,d,v),Number.isNaN($)?1:$]}throw new de(e)}function mo(e){let r=5381,a=e.length;for(;a;)r=r*33^e.charCodeAt(--a);return(r>>>0)%2341}const Pr=e=>parseInt(e.replace(/_/g,""),36),ho="1q29ehhb 1n09sgk7 1kl1ekf_ _yl4zsno 16z9eiv3 1p29lhp8 _bd9zg04 17u0____ _iw9zhe5 _to73___ _r45e31e _7l6g016 _jh8ouiv _zn3qba8 1jy4zshs 11u87k0u 1ro9yvyo 1aj3xael 1gz9zjz0 _3w8l4xo 1bf1ekf_ _ke3v___ _4rrkb__ 13j776yz _646mbhl _nrjr4__ _le6mbhl 1n37ehkb _m75f91n _qj3bzfz 1939yygw 11i5z6x8 _1k5f8xs 1509441m 15t5lwgf _ae2th1n _tg1ugcv 1lp1ugcv 16e14up_ _h55rw7n _ny9yavn _7a11xb_ 1ih442g9 _pv442g9 1mv16xof 14e6y7tu 1oo9zkds 17d1cisi _4v9y70f _y98m8kc 1019pq0v 12o9zda8 _348j4f4 1et50i2o _8epa8__ _ts6senj 1o350i2o 1mi9eiuo 1259yrp0 1ln80gnw _632xcoy 1cn9zldc _f29edu4 1n490c8q _9f9ziet 1b94vk74 _m49zkct 1kz6s73a 1eu9dtog _q58s1rz 1dy9sjiq __u89jo3 _aj5nkwg _ld89jo3 13h9z6wx _qa9z2ii _l119xgq _bs5arju 1hj4nwk9 1qt4nwk9 1ge6wau6 14j9zlcw 11p1edc_ _ms1zcxe _439shk6 _jt9y70f _754zsow 1la40eju _oq5p___ _x279qkz 1fa5r3rv _yd2d9ip _424tcku _8y1di2_ _zi2uabw _yy7rn9h 12yz980_ __39ljp6 1b59zg0x _n39zfzp 1fy9zest _b33k___ _hp9wq92 1il50hz4 _io472ub _lj9z3eo 19z9ykg0 _8t8iu3a 12b9bl4a 1ak5yw0o _896v4ku _tb8k8lv _s59zi6t _c09ze0p 1lg80oqn 1id9z8wb _238nba5 1kq6wgdi _154zssg _tn3zk49 _da9y6tc 1sg7cv4f _r12jvtt 1gq5fmkz 1cs9rvci _lp9jn1c _xw1tdnb 13f9zje6 16f6973h _vo7ir40 _bt5arjf _rc45e4t _hr4e100 10v4e100 _hc9zke2 _w91egv_ _sj2r1kk 13c87yx8 _vqpds__ _ni8ggk8 _tj9yqfb 1ia2j4r4 _7x9b10u 1fc9ld4j 1eq9zldr _5j9lhpx _ez9zl6o _md61fzm".split(" ").reduce((e,r)=>{const a=Pr(r.substring(0,3)),o=Pr(r.substring(3)).toString(16);let i="";for(let l=0;l<6-o.length;l++)i+="0";return e[a]=`${i}${o}`,e},{});function go(e){const r=e.toLowerCase().trim(),a=ho[mo(r)];if(!a)throw new de(e);return`#${a}`}const ge=(e,r)=>Array.from(Array(r)).map(()=>e).join(""),yo=new RegExp(`^#${ge("([a-f0-9])",3)}([a-f0-9])?$`,"i"),po=new RegExp(`^#${ge("([a-f0-9]{2})",3)}([a-f0-9]{2})?$`,"i"),So=new RegExp(`^rgba?\\(\\s*(\\d+)\\s*${ge(",\\s*(\\d+)\\s*",2)}(?:,\\s*([\\d.]+))?\\s*\\)$`,"i"),xo=/^hsla?\(\s*([\d.]+)\s*,\s*([\d.]+)%\s*,\s*([\d.]+)%(?:\s*,\s*([\d.]+))?\s*\)$/i,$o=/^[a-z]+$/i,Tr=e=>Math.round(e*255),ko=(e,r,a)=>{let o=a/100;if(r===0)return[o,o,o].map(Tr);const i=(e%360+360)%360/60,l=(1-Math.abs(2*o-1))*(r/100),s=l*(1-Math.abs(i%2-1));let d=0,v=0,$=0;i>=0&&i<1?(d=l,v=s):i>=1&&i<2?(d=s,v=l):i>=2&&i<3?(v=l,$=s):i>=3&&i<4?(v=s,$=l):i>=4&&i<5?(d=s,$=l):i>=5&&i<6&&(d=l,$=s);const p=o-l/2,S=d+p,T=v+p,L=$+p;return[S,T,L].map(Tr)};function _o(e,r,a,o){return`rgba(${O(0,255,e).toFixed()}, ${O(0,255,r).toFixed()}, ${O(0,255,a).toFixed()}, ${parseFloat(O(0,1,o).toFixed(3))})`}function wo(e,r){const[a,o,i,l]=xr(e);return _o(a,o,i,l-r)}function zo(e){const[r,a,o,i]=xr(e);let l=s=>{const d=O(0,255,s).toString(16);return d.length===1?`0${d}`:d};return`#${l(r)}${l(a)}${l(o)}${i<1?l(Math.round(i*255)):""}`}function Co(e,r,a,o,i){for(r=r.split?r.split("."):r,o=0;oObject.keys(e).length===0,Ne=(e,r,a)=>{const o=Co(e,`colors.${r}`,r);try{return zo(o),o}catch{return a??"#000000"}},P=(e,r,a)=>{var o;return(o=Da(e,"colors",r))!=null?o:a},Po=e=>{const[r,a,o]=xr(e);return(r*299+a*587+o*114)/1e3},To=e=>r=>{const a=Ne(r,e);return Po(a)<128?"dark":"light"},Fo=e=>r=>To(e)(r)==="dark",re=(e,r)=>a=>{const o=Ne(a,e);return wo(o,1-r)};function Fr(e="1rem",r="rgba(255, 255, 255, 0.15)"){return{backgroundImage:`linear-gradient( + 45deg, + ${r} 25%, + transparent 25%, + transparent 50%, + ${r} 50%, + ${r} 75%, + transparent 75%, + transparent + )`,backgroundSize:`${e} ${e}`}}var Io=()=>`#${Math.floor(Math.random()*16777215).toString(16).padEnd(6,"0")}`;function Mo(e){const r=Io();return!e||Ao(e)?r:e.string&&e.colors?Eo(e.string,e.colors):e.string&&!e.colors?Bo(e.string):e.colors&&!e.string?Do(e.colors):r}function Bo(e){let r=0;if(e.length===0)return r.toString();for(let o=0;o>o*8&255;a+=`00${i.toString(16)}`.substr(-2)}return a}function Eo(e,r){let a=0;if(e.length===0)return r[0];for(let o=0;or.map(pa).join(` ${e} `).replace(/calc/g,""),Ir=(...e)=>`calc(${Ke("+",...e)})`,Mr=(...e)=>`calc(${Ke("-",...e)})`,hr=(...e)=>`calc(${Ke("*",...e)})`,Br=(...e)=>`calc(${Ke("/",...e)})`,Er=e=>{const r=pa(e);return r!=null&&!Number.isNaN(parseFloat(r))?String(r).startsWith("-")?String(r).slice(1):`-${r}`:hr(r,-1)},E=Object.assign(e=>({add:(...r)=>E(Ir(e,...r)),subtract:(...r)=>E(Mr(e,...r)),multiply:(...r)=>E(hr(e,...r)),divide:(...r)=>E(Br(e,...r)),negate:()=>E(Er(e)),toString:()=>e.toString()}),{add:Ir,subtract:Mr,multiply:hr,divide:Br,negate:Er});function Ro(e){return!Number.isInteger(parseFloat(e.toString()))}function jo(e,r="-"){return e.replace(/\s+/g,r)}function Sa(e){const r=jo(e.toString());return r.includes("\\.")?e:Ro(e)?r.replace(".","\\."):e}function Ho(e,r=""){return[r,Sa(e)].filter(Boolean).join("-")}function Wo(e,r){return`var(${Sa(e)}${r?`, ${r}`:""})`}function Vo(e,r=""){return`--${Ho(e,r)}`}function m(e,r){const a=Vo(e,r==null?void 0:r.prefix);return{variable:a,reference:Wo(a,Lo(r==null?void 0:r.fallback))}}function Lo(e){return typeof e=="string"?e:e==null?void 0:e.reference}var{defineMultiStyleConfig:qo,definePartsStyle:Re}=b(so.keys),ve=m("switch-track-width"),N=m("switch-track-height"),er=m("switch-track-diff"),Oo=E.subtract(ve,N),gr=m("switch-thumb-x"),ne=m("switch-bg"),No=t(e=>{const{colorScheme:r}=e;return{borderRadius:"full",p:"0.5",width:[ve.reference],height:[N.reference],transitionProperty:"common",transitionDuration:"fast",[ne.variable]:"colors.gray.300",_dark:{[ne.variable]:"colors.whiteAlpha.400"},_focusVisible:{boxShadow:"outline"},_disabled:{opacity:.4,cursor:"not-allowed"},_checked:{[ne.variable]:`colors.${r}.500`,_dark:{[ne.variable]:`colors.${r}.200`}},bg:ne.reference}}),Go=t({bg:"white",transitionProperty:"transform",transitionDuration:"normal",borderRadius:"inherit",width:[N.reference],height:[N.reference],_checked:{transform:`translateX(${gr.reference})`}}),Uo=Re(e=>({container:{[er.variable]:Oo,[gr.variable]:er.reference,_rtl:{[gr.variable]:E(er).negate().toString()}},track:No(e),thumb:Go})),Yo={sm:Re({container:{[ve.variable]:"1.375rem",[N.variable]:"sizes.3"}}),md:Re({container:{[ve.variable]:"1.875rem",[N.variable]:"sizes.4"}}),lg:Re({container:{[ve.variable]:"2.875rem",[N.variable]:"sizes.6"}})},Xo=qo({baseStyle:Uo,sizes:Yo,defaultProps:{size:"md",colorScheme:"blue"}}),{defineMultiStyleConfig:Ko,definePartsStyle:Z}=b(co.keys),Zo=Z({table:{fontVariantNumeric:"lining-nums tabular-nums",borderCollapse:"collapse",width:"full"},th:{fontFamily:"heading",fontWeight:"bold",textTransform:"uppercase",letterSpacing:"wider",textAlign:"start"},td:{textAlign:"start"},caption:{mt:4,fontFamily:"heading",textAlign:"center",fontWeight:"medium"}}),Ge=t({"&[data-is-numeric=true]":{textAlign:"end"}}),Jo=Z(e=>{const{colorScheme:r}=e;return{th:{color:n("gray.600","gray.400")(e),borderBottom:"1px",borderColor:n(`${r}.100`,`${r}.700`)(e),...Ge},td:{borderBottom:"1px",borderColor:n(`${r}.100`,`${r}.700`)(e),...Ge},caption:{color:n("gray.600","gray.100")(e)},tfoot:{tr:{"&:last-of-type":{th:{borderBottomWidth:0}}}}}}),Qo=Z(e=>{const{colorScheme:r}=e;return{th:{color:n("gray.600","gray.400")(e),borderBottom:"1px",borderColor:n(`${r}.100`,`${r}.700`)(e),...Ge},td:{borderBottom:"1px",borderColor:n(`${r}.100`,`${r}.700`)(e),...Ge},caption:{color:n("gray.600","gray.100")(e)},tbody:{tr:{"&:nth-of-type(odd)":{"th, td":{borderBottomWidth:"1px",borderColor:n(`${r}.100`,`${r}.700`)(e)},td:{background:n(`${r}.100`,`${r}.700`)(e)}}}},tfoot:{tr:{"&:last-of-type":{th:{borderBottomWidth:0}}}}}}),en={simple:Jo,striped:Qo,unstyled:t({})},rn={sm:Z({th:{px:"4",py:"1",lineHeight:"4",fontSize:"xs"},td:{px:"4",py:"2",fontSize:"sm",lineHeight:"4"},caption:{px:"4",py:"2",fontSize:"xs"}}),md:Z({th:{px:"6",py:"3",lineHeight:"4",fontSize:"xs"},td:{px:"6",py:"4",lineHeight:"5"},caption:{px:"6",py:"2",fontSize:"sm"}}),lg:Z({th:{px:"8",py:"4",lineHeight:"5",fontSize:"sm"},td:{px:"8",py:"5",lineHeight:"6"},caption:{px:"6",py:"2",fontSize:"md"}})},an=Ko({baseStyle:Zo,variants:en,sizes:rn,defaultProps:{variant:"simple",size:"md",colorScheme:"gray"}}),_=c("tabs-color"),A=c("tabs-bg"),we=c("tabs-border-color"),{defineMultiStyleConfig:tn,definePartsStyle:M}=b(bo.keys),on=t(e=>{const{orientation:r}=e;return{display:r==="vertical"?"flex":"block"}}),nn=t(e=>{const{isFitted:r}=e;return{flex:r?1:void 0,transitionProperty:"common",transitionDuration:"normal",_focusVisible:{zIndex:1,boxShadow:"outline"},_disabled:{cursor:"not-allowed",opacity:.4}}}),ln=t(e=>{const{align:r="start",orientation:a}=e;return{justifyContent:{end:"flex-end",center:"center",start:"flex-start"}[r],flexDirection:a==="vertical"?"column":"row"}}),sn=t({p:4}),dn=M(e=>({root:on(e),tab:nn(e),tablist:ln(e),tabpanel:sn})),cn={sm:M({tab:{py:1,px:4,fontSize:"sm"}}),md:M({tab:{fontSize:"md",py:2,px:4}}),lg:M({tab:{fontSize:"lg",py:3,px:4}})},bn=M(e=>{const{colorScheme:r,orientation:a}=e,o=a==="vertical",i=o?"borderStart":"borderBottom",l=o?"marginStart":"marginBottom";return{tablist:{[i]:"2px solid",borderColor:"inherit"},tab:{[i]:"2px solid",borderColor:"transparent",[l]:"-2px",_selected:{[_.variable]:`colors.${r}.600`,_dark:{[_.variable]:`colors.${r}.300`},borderColor:"currentColor"},_active:{[A.variable]:"colors.gray.200",_dark:{[A.variable]:"colors.whiteAlpha.300"}},_disabled:{_active:{bg:"none"}},color:_.reference,bg:A.reference}}}),vn=M(e=>{const{colorScheme:r}=e;return{tab:{borderTopRadius:"md",border:"1px solid",borderColor:"transparent",mb:"-1px",[we.variable]:"transparent",_selected:{[_.variable]:`colors.${r}.600`,[we.variable]:"colors.white",_dark:{[_.variable]:`colors.${r}.300`,[we.variable]:"colors.gray.800"},borderColor:"inherit",borderBottomColor:we.reference},color:_.reference},tablist:{mb:"-1px",borderBottom:"1px solid",borderColor:"inherit"}}}),un=M(e=>{const{colorScheme:r}=e;return{tab:{border:"1px solid",borderColor:"inherit",[A.variable]:"colors.gray.50",_dark:{[A.variable]:"colors.whiteAlpha.50"},mb:"-1px",_notLast:{marginEnd:"-1px"},_selected:{[A.variable]:"colors.white",[_.variable]:`colors.${r}.600`,_dark:{[A.variable]:"colors.gray.800",[_.variable]:`colors.${r}.300`},borderColor:"inherit",borderTopColor:"currentColor",borderBottomColor:"transparent"},color:_.reference,bg:A.reference},tablist:{mb:"-1px",borderBottom:"1px solid",borderColor:"inherit"}}}),fn=M(e=>{const{colorScheme:r,theme:a}=e;return{tab:{borderRadius:"full",fontWeight:"semibold",color:"gray.600",_selected:{color:Ne(a,`${r}.700`),bg:Ne(a,`${r}.100`)}}}}),mn=M(e=>{const{colorScheme:r}=e;return{tab:{borderRadius:"full",fontWeight:"semibold",[_.variable]:"colors.gray.600",_dark:{[_.variable]:"inherit"},_selected:{[_.variable]:"colors.white",[A.variable]:`colors.${r}.600`,_dark:{[_.variable]:"colors.gray.800",[A.variable]:`colors.${r}.300`}},color:_.reference,bg:A.reference}}}),hn=M({}),gn={line:bn,enclosed:vn,"enclosed-colored":un,"soft-rounded":fn,"solid-rounded":mn,unstyled:hn},yn=tn({baseStyle:dn,sizes:cn,variants:gn,defaultProps:{size:"md",variant:"line",colorScheme:"blue"}}),y=Ra("badge",["bg","color","shadow"]),pn=t({px:1,textTransform:"uppercase",fontSize:"xs",borderRadius:"sm",fontWeight:"bold",bg:y.bg.reference,color:y.color.reference,boxShadow:y.shadow.reference}),Sn=t(e=>{const{colorScheme:r,theme:a}=e,o=re(`${r}.500`,.6)(a);return{[y.bg.variable]:`colors.${r}.500`,[y.color.variable]:"colors.white",_dark:{[y.bg.variable]:o,[y.color.variable]:"colors.whiteAlpha.800"}}}),xn=t(e=>{const{colorScheme:r,theme:a}=e,o=re(`${r}.200`,.16)(a);return{[y.bg.variable]:`colors.${r}.100`,[y.color.variable]:`colors.${r}.800`,_dark:{[y.bg.variable]:o,[y.color.variable]:`colors.${r}.200`}}}),$n=t(e=>{const{colorScheme:r,theme:a}=e,o=re(`${r}.200`,.8)(a);return{[y.color.variable]:`colors.${r}.500`,_dark:{[y.color.variable]:o},[y.shadow.variable]:`inset 0 0 0px 1px ${y.color.reference}`}}),kn={solid:Sn,subtle:xn,outline:$n},ue=h({baseStyle:pn,variants:kn,defaultProps:{variant:"subtle",colorScheme:"gray"}}),{defineMultiStyleConfig:_n,definePartsStyle:G}=b(vo.keys),Dr=c("tag-bg"),Rr=c("tag-color"),rr=c("tag-shadow"),je=c("tag-min-height"),He=c("tag-min-width"),We=c("tag-font-size"),Ve=c("tag-padding-inline"),wn=t({fontWeight:"medium",lineHeight:1.2,outline:0,[Rr.variable]:y.color.reference,[Dr.variable]:y.bg.reference,[rr.variable]:y.shadow.reference,color:Rr.reference,bg:Dr.reference,boxShadow:rr.reference,borderRadius:"md",minH:je.reference,minW:He.reference,fontSize:We.reference,px:Ve.reference,_focusVisible:{[rr.variable]:"shadows.outline"}}),zn=t({lineHeight:1.2,overflow:"visible"}),Cn=t({fontSize:"lg",w:"5",h:"5",transitionProperty:"common",transitionDuration:"normal",borderRadius:"full",marginStart:"1.5",marginEnd:"-1",opacity:.5,_disabled:{opacity:.4},_focusVisible:{boxShadow:"outline",bg:"rgba(0, 0, 0, 0.14)"},_hover:{opacity:.8},_active:{opacity:1}}),An=G({container:wn,label:zn,closeButton:Cn}),Pn={sm:G({container:{[je.variable]:"sizes.5",[He.variable]:"sizes.5",[We.variable]:"fontSizes.xs",[Ve.variable]:"space.2"},closeButton:{marginEnd:"-2px",marginStart:"0.35rem"}}),md:G({container:{[je.variable]:"sizes.6",[He.variable]:"sizes.6",[We.variable]:"fontSizes.sm",[Ve.variable]:"space.2"}}),lg:G({container:{[je.variable]:"sizes.8",[He.variable]:"sizes.8",[We.variable]:"fontSizes.md",[Ve.variable]:"space.3"}})},Tn={subtle:G(e=>{var r;return{container:(r=ue.variants)==null?void 0:r.subtle(e)}}),solid:G(e=>{var r;return{container:(r=ue.variants)==null?void 0:r.solid(e)}}),outline:G(e=>{var r;return{container:(r=ue.variants)==null?void 0:r.outline(e)}})},Fn=_n({variants:Tn,baseStyle:An,sizes:Pn,defaultProps:{size:"md",variant:"subtle",colorScheme:"gray"}}),{definePartsStyle:D,defineMultiStyleConfig:In}=b(Zt.keys),Mn=D({field:{width:"100%",minWidth:0,outline:0,position:"relative",appearance:"none",transitionProperty:"common",transitionDuration:"normal",_disabled:{opacity:.4,cursor:"not-allowed"}}}),H={lg:t({fontSize:"lg",px:"4",h:"12",borderRadius:"md"}),md:t({fontSize:"md",px:"4",h:"10",borderRadius:"md"}),sm:t({fontSize:"sm",px:"3",h:"8",borderRadius:"sm"}),xs:t({fontSize:"xs",px:"2",h:"6",borderRadius:"sm"})},Bn={lg:D({field:H.lg,addon:H.lg}),md:D({field:H.md,addon:H.md}),sm:D({field:H.sm,addon:H.sm}),xs:D({field:H.xs,addon:H.xs})};function $r(e){const{focusBorderColor:r,errorBorderColor:a}=e;return{focusBorderColor:r||n("blue.500","blue.300")(e),errorBorderColor:a||n("red.500","red.300")(e)}}var En=D(e=>{const{theme:r}=e,{focusBorderColor:a,errorBorderColor:o}=$r(e);return{field:{border:"1px solid",borderColor:"inherit",bg:"inherit",_hover:{borderColor:n("gray.300","whiteAlpha.400")(e)},_readOnly:{boxShadow:"none !important",userSelect:"all"},_invalid:{borderColor:P(r,o),boxShadow:`0 0 0 1px ${P(r,o)}`},_focusVisible:{zIndex:1,borderColor:P(r,a),boxShadow:`0 0 0 1px ${P(r,a)}`}},addon:{border:"1px solid",borderColor:n("inherit","whiteAlpha.50")(e),bg:n("gray.100","whiteAlpha.300")(e)}}}),Dn=D(e=>{const{theme:r}=e,{focusBorderColor:a,errorBorderColor:o}=$r(e);return{field:{border:"2px solid",borderColor:"transparent",bg:n("gray.100","whiteAlpha.50")(e),_hover:{bg:n("gray.200","whiteAlpha.100")(e)},_readOnly:{boxShadow:"none !important",userSelect:"all"},_invalid:{borderColor:P(r,o)},_focusVisible:{bg:"transparent",borderColor:P(r,a)}},addon:{border:"2px solid",borderColor:"transparent",bg:n("gray.100","whiteAlpha.50")(e)}}}),Rn=D(e=>{const{theme:r}=e,{focusBorderColor:a,errorBorderColor:o}=$r(e);return{field:{borderBottom:"1px solid",borderColor:"inherit",borderRadius:"0",px:"0",bg:"transparent",_readOnly:{boxShadow:"none !important",userSelect:"all"},_invalid:{borderColor:P(r,o),boxShadow:`0px 1px 0px 0px ${P(r,o)}`},_focusVisible:{borderColor:P(r,a),boxShadow:`0px 1px 0px 0px ${P(r,a)}`}},addon:{borderBottom:"2px solid",borderColor:"inherit",borderRadius:"0",px:"0",bg:"transparent"}}}),jn=D({field:{bg:"transparent",px:"0",height:"auto"},addon:{bg:"transparent",px:"0",height:"auto"}}),Hn={outline:En,filled:Dn,flushed:Rn,unstyled:jn},u=In({baseStyle:Mn,sizes:Bn,variants:Hn,defaultProps:{size:"md",variant:"outline"}}),jr,Wn=t({...(jr=u.baseStyle)==null?void 0:jr.field,paddingY:"2",minHeight:"20",lineHeight:"short",verticalAlign:"top"}),Hr,Wr,Vn={outline:t(e=>{var r,a;return(a=(r=u.variants)==null?void 0:r.outline(e).field)!=null?a:{}}),flushed:t(e=>{var r,a;return(a=(r=u.variants)==null?void 0:r.flushed(e).field)!=null?a:{}}),filled:t(e=>{var r,a;return(a=(r=u.variants)==null?void 0:r.filled(e).field)!=null?a:{}}),unstyled:(Wr=(Hr=u.variants)==null?void 0:Hr.unstyled.field)!=null?Wr:{}},Vr,Lr,qr,Or,Nr,Gr,Ur,Yr,Ln={xs:(Lr=(Vr=u.sizes)==null?void 0:Vr.xs.field)!=null?Lr:{},sm:(Or=(qr=u.sizes)==null?void 0:qr.sm.field)!=null?Or:{},md:(Gr=(Nr=u.sizes)==null?void 0:Nr.md.field)!=null?Gr:{},lg:(Yr=(Ur=u.sizes)==null?void 0:Ur.lg.field)!=null?Yr:{}},qn=h({baseStyle:Wn,sizes:Ln,variants:Vn,defaultProps:{size:"md",variant:"outline"}}),ze=m("tooltip-bg"),ar=m("tooltip-fg"),On=m("popper-arrow-bg"),Nn=t({bg:ze.reference,color:ar.reference,[ze.variable]:"colors.gray.700",[ar.variable]:"colors.whiteAlpha.900",_dark:{[ze.variable]:"colors.gray.300",[ar.variable]:"colors.gray.900"},[On.variable]:ze.reference,px:"2",py:"0.5",borderRadius:"sm",fontWeight:"medium",fontSize:"sm",boxShadow:"md",maxW:"xs",zIndex:"tooltip"}),Gn=h({baseStyle:Nn}),{defineMultiStyleConfig:Un,definePartsStyle:ce}=b(to.keys),Yn=t(e=>{const{colorScheme:r,theme:a,isIndeterminate:o,hasStripe:i}=e,l=n(Fr(),Fr("1rem","rgba(0,0,0,0.1)"))(e),s=n(`${r}.500`,`${r}.200`)(e),d=`linear-gradient( + to right, + transparent 0%, + ${P(a,s)} 50%, + transparent 100% + )`;return{...!o&&i&&l,...o?{bgImage:d}:{bgColor:s}}}),Xn=t({lineHeight:"1",fontSize:"0.25em",fontWeight:"bold",color:"white"}),Kn=t(e=>({bg:n("gray.100","whiteAlpha.300")(e)})),Zn=t(e=>({transitionProperty:"common",transitionDuration:"slow",...Yn(e)})),Jn=ce(e=>({label:Xn,filledTrack:Zn(e),track:Kn(e)})),Qn={xs:ce({track:{h:"1"}}),sm:ce({track:{h:"2"}}),md:ce({track:{h:"3"}}),lg:ce({track:{h:"4"}})},ei=Un({sizes:Qn,baseStyle:Jn,defaultProps:{size:"md",colorScheme:"blue"}}),ri=e=>typeof e=="function";function k(e,...r){return ri(e)?e(...r):e}var{definePartsStyle:Le,defineMultiStyleConfig:ai}=b(Gt.keys),fe=c("checkbox-size"),ti=t(e=>{const{colorScheme:r}=e;return{w:fe.reference,h:fe.reference,transitionProperty:"box-shadow",transitionDuration:"normal",border:"2px solid",borderRadius:"sm",borderColor:"inherit",color:"white",_checked:{bg:n(`${r}.500`,`${r}.200`)(e),borderColor:n(`${r}.500`,`${r}.200`)(e),color:n("white","gray.900")(e),_hover:{bg:n(`${r}.600`,`${r}.300`)(e),borderColor:n(`${r}.600`,`${r}.300`)(e)},_disabled:{borderColor:n("gray.200","transparent")(e),bg:n("gray.200","whiteAlpha.300")(e),color:n("gray.500","whiteAlpha.500")(e)}},_indeterminate:{bg:n(`${r}.500`,`${r}.200`)(e),borderColor:n(`${r}.500`,`${r}.200`)(e),color:n("white","gray.900")(e)},_disabled:{bg:n("gray.100","whiteAlpha.100")(e),borderColor:n("gray.100","transparent")(e)},_focusVisible:{boxShadow:"outline"},_invalid:{borderColor:n("red.500","red.300")(e)}}}),oi=t({_disabled:{cursor:"not-allowed"}}),ni=t({userSelect:"none",_disabled:{opacity:.4}}),ii=t({transitionProperty:"transform",transitionDuration:"normal"}),li=Le(e=>({icon:ii,container:oi,control:k(ti,e),label:ni})),si={sm:Le({control:{[fe.variable]:"sizes.3"},label:{fontSize:"sm"},icon:{fontSize:"3xs"}}),md:Le({control:{[fe.variable]:"sizes.4"},label:{fontSize:"md"},icon:{fontSize:"2xs"}}),lg:Le({control:{[fe.variable]:"sizes.5"},label:{fontSize:"lg"},icon:{fontSize:"2xs"}})},Ue=ai({baseStyle:li,sizes:si,defaultProps:{size:"md",colorScheme:"blue"}}),{defineMultiStyleConfig:di,definePartsStyle:qe}=b(oo.keys),ci=t(e=>{var r;const a=(r=k(Ue.baseStyle,e))==null?void 0:r.control;return{...a,borderRadius:"full",_checked:{...a==null?void 0:a._checked,_before:{content:'""',display:"inline-block",pos:"relative",w:"50%",h:"50%",borderRadius:"50%",bg:"currentColor"}}}}),bi=qe(e=>{var r,a,o,i;return{label:(a=(r=Ue).baseStyle)==null?void 0:a.call(r,e).label,container:(i=(o=Ue).baseStyle)==null?void 0:i.call(o,e).container,control:ci(e)}}),vi={md:qe({control:{w:"4",h:"4"},label:{fontSize:"md"}}),lg:qe({control:{w:"5",h:"5"},label:{fontSize:"lg"}}),sm:qe({control:{width:"3",height:"3"},label:{fontSize:"sm"}})},ui=di({baseStyle:bi,sizes:vi,defaultProps:{size:"md",colorScheme:"blue"}}),{defineMultiStyleConfig:fi,definePartsStyle:mi}=b(no.keys),Ce=c("select-bg"),Xr,hi=t({...(Xr=u.baseStyle)==null?void 0:Xr.field,appearance:"none",paddingBottom:"1px",lineHeight:"normal",bg:Ce.reference,[Ce.variable]:"colors.white",_dark:{[Ce.variable]:"colors.gray.700"},"> option, > optgroup":{bg:Ce.reference}}),gi=t({width:"6",height:"100%",insetEnd:"2",position:"relative",color:"currentColor",fontSize:"xl",_disabled:{opacity:.5}}),yi=mi({field:hi,icon:gi}),Ae=t({paddingInlineEnd:"8"}),Kr,Zr,Jr,Qr,ea,ra,aa,ta,pi={lg:{...(Kr=u.sizes)==null?void 0:Kr.lg,field:{...(Zr=u.sizes)==null?void 0:Zr.lg.field,...Ae}},md:{...(Jr=u.sizes)==null?void 0:Jr.md,field:{...(Qr=u.sizes)==null?void 0:Qr.md.field,...Ae}},sm:{...(ea=u.sizes)==null?void 0:ea.sm,field:{...(ra=u.sizes)==null?void 0:ra.sm.field,...Ae}},xs:{...(aa=u.sizes)==null?void 0:aa.xs,field:{...(ta=u.sizes)==null?void 0:ta.xs.field,...Ae},icon:{insetEnd:"1"}}},Si=fi({baseStyle:yi,sizes:pi,variants:u.variants,defaultProps:u.defaultProps}),tr=c("skeleton-start-color"),or=c("skeleton-end-color"),xi=t({[tr.variable]:"colors.gray.100",[or.variable]:"colors.gray.400",_dark:{[tr.variable]:"colors.gray.800",[or.variable]:"colors.gray.600"},background:tr.reference,borderColor:or.reference,opacity:.7,borderRadius:"sm"}),$i=h({baseStyle:xi}),nr=c("skip-link-bg"),ki=t({borderRadius:"md",fontWeight:"semibold",_focusVisible:{boxShadow:"outline",padding:"4",position:"fixed",top:"6",insetStart:"6",[nr.variable]:"colors.white",_dark:{[nr.variable]:"colors.gray.700"},bg:nr.reference}}),_i=h({baseStyle:ki}),{defineMultiStyleConfig:wi,definePartsStyle:Ze}=b(io.keys),ye=c("slider-thumb-size"),pe=c("slider-track-size"),V=c("slider-bg"),zi=t(e=>{const{orientation:r}=e;return{display:"inline-block",position:"relative",cursor:"pointer",_disabled:{opacity:.6,cursor:"default",pointerEvents:"none"},...Sr({orientation:r,vertical:{h:"100%"},horizontal:{w:"100%"}})}}),Ci=t(e=>({...Sr({orientation:e.orientation,horizontal:{h:pe.reference},vertical:{w:pe.reference}}),overflow:"hidden",borderRadius:"sm",[V.variable]:"colors.gray.200",_dark:{[V.variable]:"colors.whiteAlpha.200"},_disabled:{[V.variable]:"colors.gray.300",_dark:{[V.variable]:"colors.whiteAlpha.300"}},bg:V.reference})),Ai=t(e=>{const{orientation:r}=e;return{...Sr({orientation:r,vertical:{left:"50%",transform:"translateX(-50%)",_active:{transform:"translateX(-50%) scale(1.15)"}},horizontal:{top:"50%",transform:"translateY(-50%)",_active:{transform:"translateY(-50%) scale(1.15)"}}}),w:ye.reference,h:ye.reference,display:"flex",alignItems:"center",justifyContent:"center",position:"absolute",outline:0,zIndex:1,borderRadius:"full",bg:"white",boxShadow:"base",border:"1px solid",borderColor:"transparent",transitionProperty:"transform",transitionDuration:"normal",_focusVisible:{boxShadow:"outline"},_disabled:{bg:"gray.300"}}}),Pi=t(e=>{const{colorScheme:r}=e;return{width:"inherit",height:"inherit",[V.variable]:`colors.${r}.500`,_dark:{[V.variable]:`colors.${r}.200`},bg:V.reference}}),Ti=Ze(e=>({container:zi(e),track:Ci(e),thumb:Ai(e),filledTrack:Pi(e)})),Fi=Ze({container:{[ye.variable]:"sizes.4",[pe.variable]:"sizes.1"}}),Ii=Ze({container:{[ye.variable]:"sizes.3.5",[pe.variable]:"sizes.1"}}),Mi=Ze({container:{[ye.variable]:"sizes.2.5",[pe.variable]:"sizes.0.5"}}),Bi={lg:Fi,md:Ii,sm:Mi},Ei=wi({baseStyle:Ti,sizes:Bi,defaultProps:{size:"md",colorScheme:"blue"}}),q=m("spinner-size"),Di=t({width:[q.reference],height:[q.reference]}),Ri={xs:t({[q.variable]:"sizes.3"}),sm:t({[q.variable]:"sizes.4"}),md:t({[q.variable]:"sizes.6"}),lg:t({[q.variable]:"sizes.8"}),xl:t({[q.variable]:"sizes.12"})},ji=h({baseStyle:Di,sizes:Ri,defaultProps:{size:"md"}}),{defineMultiStyleConfig:Hi,definePartsStyle:xa}=b(lo.keys),Wi=t({fontWeight:"medium"}),Vi=t({opacity:.8,marginBottom:"2"}),Li=t({verticalAlign:"baseline",fontWeight:"semibold"}),qi=t({marginEnd:1,w:"3.5",h:"3.5",verticalAlign:"middle"}),Oi=xa({container:{},label:Wi,helpText:Vi,number:Li,icon:qi}),Ni={md:xa({label:{fontSize:"sm"},helpText:{fontSize:"sm"},number:{fontSize:"2xl"}})},Gi=Hi({baseStyle:Oi,sizes:Ni,defaultProps:{size:"md"}}),ir=c("kbd-bg"),Ui=t({[ir.variable]:"colors.gray.100",_dark:{[ir.variable]:"colors.whiteAlpha.100"},bg:ir.reference,borderRadius:"md",borderWidth:"1px",borderBottomWidth:"3px",fontSize:"0.8em",fontWeight:"bold",lineHeight:"normal",px:"0.4em",whiteSpace:"nowrap"}),Yi=h({baseStyle:Ui}),Xi=t({transitionProperty:"common",transitionDuration:"fast",transitionTimingFunction:"ease-out",cursor:"pointer",textDecoration:"none",outline:"none",color:"inherit",_hover:{textDecoration:"underline"},_focusVisible:{boxShadow:"outline"}}),Ki=h({baseStyle:Xi}),{defineMultiStyleConfig:Zi,definePartsStyle:Ji}=b(Jt.keys),Qi=t({marginEnd:"2",display:"inline",verticalAlign:"text-bottom"}),el=Ji({icon:Qi}),rl=Zi({baseStyle:el}),{defineMultiStyleConfig:al,definePartsStyle:tl}=b(Qt.keys),I=c("menu-bg"),lr=c("menu-shadow"),ol=t({[I.variable]:"#fff",[lr.variable]:"shadows.sm",_dark:{[I.variable]:"colors.gray.700",[lr.variable]:"shadows.dark-lg"},color:"inherit",minW:"3xs",py:"2",zIndex:1,borderRadius:"md",borderWidth:"1px",bg:I.reference,boxShadow:lr.reference}),nl=t({py:"1.5",px:"3",transitionProperty:"background",transitionDuration:"ultra-fast",transitionTimingFunction:"ease-in",_focus:{[I.variable]:"colors.gray.100",_dark:{[I.variable]:"colors.whiteAlpha.100"}},_active:{[I.variable]:"colors.gray.200",_dark:{[I.variable]:"colors.whiteAlpha.200"}},_expanded:{[I.variable]:"colors.gray.100",_dark:{[I.variable]:"colors.whiteAlpha.100"}},_disabled:{opacity:.4,cursor:"not-allowed"},bg:I.reference}),il=t({mx:4,my:2,fontWeight:"semibold",fontSize:"sm"}),ll=t({opacity:.6}),sl=t({border:0,borderBottom:"1px solid",borderColor:"inherit",my:"2",opacity:.6}),dl=t({transitionProperty:"common",transitionDuration:"normal"}),cl=tl({button:dl,list:ol,item:nl,groupTitle:il,command:ll,divider:sl}),bl=al({baseStyle:cl}),{defineMultiStyleConfig:vl,definePartsStyle:yr}=b(eo.keys),sr=c("modal-bg"),dr=c("modal-shadow"),ul=t({bg:"blackAlpha.600",zIndex:"modal"}),fl=t(e=>{const{isCentered:r,scrollBehavior:a}=e;return{display:"flex",zIndex:"modal",justifyContent:"center",alignItems:r?"center":"flex-start",overflow:a==="inside"?"hidden":"auto",overscrollBehaviorY:"none"}}),ml=t(e=>{const{isCentered:r,scrollBehavior:a}=e;return{borderRadius:"md",color:"inherit",my:r?"auto":"16",mx:r?"auto":void 0,zIndex:"modal",maxH:a==="inside"?"calc(100% - 7.5rem)":void 0,[sr.variable]:"colors.white",[dr.variable]:"shadows.lg",_dark:{[sr.variable]:"colors.gray.700",[dr.variable]:"shadows.dark-lg"},bg:sr.reference,boxShadow:dr.reference}}),hl=t({px:"6",py:"4",fontSize:"xl",fontWeight:"semibold"}),gl=t({position:"absolute",top:"2",insetEnd:"3"}),yl=t(e=>{const{scrollBehavior:r}=e;return{px:"6",py:"2",flex:"1",overflow:r==="inside"?"auto":void 0}}),pl=t({px:"6",py:"4"}),Sl=yr(e=>({overlay:ul,dialogContainer:k(fl,e),dialog:k(ml,e),header:hl,closeButton:gl,body:k(yl,e),footer:pl}));function C(e){return yr(e==="full"?{dialog:{maxW:"100vw",minH:"$100vh",my:"0",borderRadius:"0"}}:{dialog:{maxW:e}})}var xl={xs:C("xs"),sm:C("sm"),md:C("md"),lg:C("lg"),xl:C("xl"),"2xl":C("2xl"),"3xl":C("3xl"),"4xl":C("4xl"),"5xl":C("5xl"),"6xl":C("6xl"),full:C("full")},$l=vl({baseStyle:Sl,sizes:xl,defaultProps:{size:"md"}}),{defineMultiStyleConfig:kl,definePartsStyle:$a}=b(ro.keys),kr=m("number-input-stepper-width"),ka=m("number-input-input-padding"),_l=E(kr).add("0.5rem").toString(),cr=m("number-input-bg"),br=m("number-input-color"),vr=m("number-input-border-color"),wl=t({[kr.variable]:"sizes.6",[ka.variable]:_l}),zl=t(e=>{var r,a;return(a=(r=k(u.baseStyle,e))==null?void 0:r.field)!=null?a:{}}),Cl=t({width:kr.reference}),Al=t({borderStart:"1px solid",borderStartColor:vr.reference,color:br.reference,bg:cr.reference,[br.variable]:"colors.chakra-body-text",[vr.variable]:"colors.chakra-border-color",_dark:{[br.variable]:"colors.whiteAlpha.800",[vr.variable]:"colors.whiteAlpha.300"},_active:{[cr.variable]:"colors.gray.200",_dark:{[cr.variable]:"colors.whiteAlpha.300"}},_disabled:{opacity:.4,cursor:"not-allowed"}}),Pl=$a(e=>{var r;return{root:wl,field:(r=k(zl,e))!=null?r:{},stepperGroup:Cl,stepper:Al}});function Pe(e){var r,a,o;const i=(r=u.sizes)==null?void 0:r[e],l={lg:"md",md:"md",sm:"sm",xs:"sm"},s=(o=(a=i.field)==null?void 0:a.fontSize)!=null?o:"md",d=ha.fontSizes[s];return $a({field:{...i.field,paddingInlineEnd:ka.reference,verticalAlign:"top"},stepper:{fontSize:E(d).multiply(.75).toString(),_first:{borderTopEndRadius:l[e]},_last:{borderBottomEndRadius:l[e],mt:"-1px",borderTopWidth:1}}})}var Tl={xs:Pe("xs"),sm:Pe("sm"),md:Pe("md"),lg:Pe("lg")},Fl=kl({baseStyle:Pl,sizes:Tl,variants:u.variants,defaultProps:u.defaultProps}),oa,Il=t({...(oa=u.baseStyle)==null?void 0:oa.field,textAlign:"center"}),Ml={lg:t({fontSize:"lg",w:12,h:12,borderRadius:"md"}),md:t({fontSize:"md",w:10,h:10,borderRadius:"md"}),sm:t({fontSize:"sm",w:8,h:8,borderRadius:"sm"}),xs:t({fontSize:"xs",w:6,h:6,borderRadius:"sm"})},na,ia,Bl={outline:t(e=>{var r,a,o;return(o=(a=k((r=u.variants)==null?void 0:r.outline,e))==null?void 0:a.field)!=null?o:{}}),flushed:t(e=>{var r,a,o;return(o=(a=k((r=u.variants)==null?void 0:r.flushed,e))==null?void 0:a.field)!=null?o:{}}),filled:t(e=>{var r,a,o;return(o=(a=k((r=u.variants)==null?void 0:r.filled,e))==null?void 0:a.field)!=null?o:{}}),unstyled:(ia=(na=u.variants)==null?void 0:na.unstyled.field)!=null?ia:{}},El=h({baseStyle:Il,sizes:Ml,variants:Bl,defaultProps:u.defaultProps}),{defineMultiStyleConfig:Dl,definePartsStyle:Rl}=b(ao.keys),Te=m("popper-bg"),jl=m("popper-arrow-bg"),la=m("popper-arrow-shadow-color"),Hl=t({zIndex:10}),Wl=t({[Te.variable]:"colors.white",bg:Te.reference,[jl.variable]:Te.reference,[la.variable]:"colors.gray.200",_dark:{[Te.variable]:"colors.gray.700",[la.variable]:"colors.whiteAlpha.300"},width:"xs",border:"1px solid",borderColor:"inherit",borderRadius:"md",boxShadow:"sm",zIndex:"inherit",_focusVisible:{outline:0,boxShadow:"outline"}}),Vl=t({px:3,py:2,borderBottomWidth:"1px"}),Ll=t({px:3,py:2}),ql=t({px:3,py:2,borderTopWidth:"1px"}),Ol=t({position:"absolute",borderRadius:"md",top:1,insetEnd:2,padding:2}),Nl=Rl({popper:Hl,content:Wl,header:Vl,body:Ll,footer:ql,closeButton:Ol}),Gl=Dl({baseStyle:Nl}),{definePartsStyle:pr,defineMultiStyleConfig:Ul}=b(Ut.keys),ur=c("drawer-bg"),fr=c("drawer-box-shadow");function Y(e){return pr(e==="full"?{dialog:{maxW:"100vw",h:"100vh"}}:{dialog:{maxW:e}})}var Yl=t({bg:"blackAlpha.600",zIndex:"overlay"}),Xl=t({display:"flex",zIndex:"modal",justifyContent:"center"}),Kl=t(e=>{const{isFullHeight:r}=e;return{...r&&{height:"100vh"},zIndex:"modal",maxH:"100vh",color:"inherit",[ur.variable]:"colors.white",[fr.variable]:"shadows.lg",_dark:{[ur.variable]:"colors.gray.700",[fr.variable]:"shadows.dark-lg"},bg:ur.reference,boxShadow:fr.reference}}),Zl=t({px:"6",py:"4",fontSize:"xl",fontWeight:"semibold"}),Jl=t({position:"absolute",top:"2",insetEnd:"3"}),Ql=t({px:"6",py:"2",flex:"1",overflow:"auto"}),es=t({px:"6",py:"4"}),rs=pr(e=>({overlay:Yl,dialogContainer:Xl,dialog:k(Kl,e),header:Zl,closeButton:Jl,body:Ql,footer:es})),as={xs:Y("xs"),sm:Y("md"),md:Y("lg"),lg:Y("2xl"),xl:Y("4xl"),full:Y("full")},ts=Ul({baseStyle:rs,sizes:as,defaultProps:{size:"xs"}}),{definePartsStyle:os,defineMultiStyleConfig:ns}=b(Yt.keys),is=t({borderRadius:"md",py:"1",transitionProperty:"common",transitionDuration:"normal"}),ls=t({borderRadius:"md",py:"1",transitionProperty:"common",transitionDuration:"normal",width:"full",_focusVisible:{boxShadow:"outline"},_placeholder:{opacity:.6}}),ss=t({borderRadius:"md",py:"1",transitionProperty:"common",transitionDuration:"normal",width:"full",_focusVisible:{boxShadow:"outline"},_placeholder:{opacity:.6}}),ds=os({preview:is,input:ls,textarea:ss}),cs=ns({baseStyle:ds}),{definePartsStyle:bs,defineMultiStyleConfig:vs}=b(Xt.keys),J=c("form-control-color"),us=t({marginStart:"1",[J.variable]:"colors.red.500",_dark:{[J.variable]:"colors.red.300"},color:J.reference}),fs=t({mt:"2",[J.variable]:"colors.gray.600",_dark:{[J.variable]:"colors.whiteAlpha.600"},color:J.reference,lineHeight:"normal",fontSize:"sm"}),ms=bs({container:{width:"100%",position:"relative"},requiredIndicator:us,helperText:fs}),hs=vs({baseStyle:ms}),{definePartsStyle:gs,defineMultiStyleConfig:ys}=b(Kt.keys),Q=c("form-error-color"),ps=t({[Q.variable]:"colors.red.500",_dark:{[Q.variable]:"colors.red.300"},color:Q.reference,mt:"2",fontSize:"sm",lineHeight:"normal"}),Ss=t({marginEnd:"0.5em",[Q.variable]:"colors.red.500",_dark:{[Q.variable]:"colors.red.300"},color:Q.reference}),xs=gs({text:ps,icon:Ss}),$s=ys({baseStyle:xs}),ks=t({fontSize:"md",marginEnd:"3",mb:"2",fontWeight:"medium",transitionProperty:"common",transitionDuration:"normal",opacity:1,_disabled:{opacity:.4}}),_s=h({baseStyle:ks}),ws=t({fontFamily:"heading",fontWeight:"bold"}),zs={"4xl":t({fontSize:["6xl",null,"7xl"],lineHeight:1}),"3xl":t({fontSize:["5xl",null,"6xl"],lineHeight:1}),"2xl":t({fontSize:["4xl",null,"5xl"],lineHeight:[1.2,null,1]}),xl:t({fontSize:["3xl",null,"4xl"],lineHeight:[1.33,null,1.2]}),lg:t({fontSize:["2xl",null,"3xl"],lineHeight:[1.33,null,1.2]}),md:t({fontSize:"xl",lineHeight:1.2}),sm:t({fontSize:"md",lineHeight:1.2}),xs:t({fontSize:"sm",lineHeight:1.2})},Cs=h({baseStyle:ws,sizes:zs,defaultProps:{size:"xl"}}),{defineMultiStyleConfig:As,definePartsStyle:Ps}=b(Nt.keys),mr=c("breadcrumb-link-decor"),Ts=t({transitionProperty:"common",transitionDuration:"fast",transitionTimingFunction:"ease-out",outline:"none",color:"inherit",textDecoration:mr.reference,[mr.variable]:"none","&:not([aria-current=page])":{cursor:"pointer",_hover:{[mr.variable]:"underline"},_focusVisible:{boxShadow:"outline"}}}),Fs=Ps({link:Ts}),Is=As({baseStyle:Fs}),Ms=t({lineHeight:"1.2",borderRadius:"md",fontWeight:"semibold",transitionProperty:"common",transitionDuration:"normal",_focusVisible:{boxShadow:"outline"},_disabled:{opacity:.4,cursor:"not-allowed",boxShadow:"none"},_hover:{_disabled:{bg:"initial"}}}),_a=t(e=>{const{colorScheme:r,theme:a}=e;if(r==="gray")return{color:n("gray.800","whiteAlpha.900")(e),_hover:{bg:n("gray.100","whiteAlpha.200")(e)},_active:{bg:n("gray.200","whiteAlpha.300")(e)}};const o=re(`${r}.200`,.12)(a),i=re(`${r}.200`,.24)(a);return{color:n(`${r}.600`,`${r}.200`)(e),bg:"transparent",_hover:{bg:n(`${r}.50`,o)(e)},_active:{bg:n(`${r}.100`,i)(e)}}}),Bs=t(e=>{const{colorScheme:r}=e,a=n("gray.200","whiteAlpha.300")(e);return{border:"1px solid",borderColor:r==="gray"?a:"currentColor",".chakra-button__group[data-attached][data-orientation=horizontal] > &:not(:last-of-type)":{marginEnd:"-1px"},".chakra-button__group[data-attached][data-orientation=vertical] > &:not(:last-of-type)":{marginBottom:"-1px"},...k(_a,e)}}),Es={yellow:{bg:"yellow.400",color:"black",hoverBg:"yellow.500",activeBg:"yellow.600"},cyan:{bg:"cyan.400",color:"black",hoverBg:"cyan.500",activeBg:"cyan.600"}},Ds=t(e=>{var r;const{colorScheme:a}=e;if(a==="gray"){const v=n("gray.100","whiteAlpha.200")(e);return{bg:v,color:n("gray.800","whiteAlpha.900")(e),_hover:{bg:n("gray.200","whiteAlpha.300")(e),_disabled:{bg:v}},_active:{bg:n("gray.300","whiteAlpha.400")(e)}}}const{bg:o=`${a}.500`,color:i="white",hoverBg:l=`${a}.600`,activeBg:s=`${a}.700`}=(r=Es[a])!=null?r:{},d=n(o,`${a}.200`)(e);return{bg:d,color:n(i,"gray.800")(e),_hover:{bg:n(l,`${a}.300`)(e),_disabled:{bg:d}},_active:{bg:n(s,`${a}.400`)(e)}}}),Rs=t(e=>{const{colorScheme:r}=e;return{padding:0,height:"auto",lineHeight:"normal",verticalAlign:"baseline",color:n(`${r}.500`,`${r}.200`)(e),_hover:{textDecoration:"underline",_disabled:{textDecoration:"none"}},_active:{color:n(`${r}.700`,`${r}.500`)(e)}}}),js=t({bg:"none",color:"inherit",display:"inline",lineHeight:"inherit",m:"0",p:"0"}),Hs={ghost:_a,outline:Bs,solid:Ds,link:Rs,unstyled:js},Ws={lg:t({h:"12",minW:"12",fontSize:"lg",px:"6"}),md:t({h:"10",minW:"10",fontSize:"md",px:"4"}),sm:t({h:"8",minW:"8",fontSize:"sm",px:"3"}),xs:t({h:"6",minW:"6",fontSize:"xs",px:"2"})},Vs=h({baseStyle:Ms,variants:Hs,sizes:Ws,defaultProps:{variant:"solid",size:"md",colorScheme:"gray"}}),{definePartsStyle:U,defineMultiStyleConfig:Ls}=b(uo.keys),Ye=c("card-bg"),R=c("card-padding"),wa=c("card-shadow"),Oe=c("card-radius"),za=c("card-border-width","0"),Ca=c("card-border-color"),qs=U({container:{[Ye.variable]:"colors.chakra-body-bg",backgroundColor:Ye.reference,boxShadow:wa.reference,borderRadius:Oe.reference,color:"chakra-body-text",borderWidth:za.reference,borderColor:Ca.reference},body:{padding:R.reference,flex:"1 1 0%"},header:{padding:R.reference},footer:{padding:R.reference}}),Os={sm:U({container:{[Oe.variable]:"radii.base",[R.variable]:"space.3"}}),md:U({container:{[Oe.variable]:"radii.md",[R.variable]:"space.5"}}),lg:U({container:{[Oe.variable]:"radii.xl",[R.variable]:"space.7"}})},Ns={elevated:U({container:{[wa.variable]:"shadows.base",_dark:{[Ye.variable]:"colors.gray.700"}}}),outline:U({container:{[za.variable]:"1px",[Ca.variable]:"colors.chakra-border-color"}}),filled:U({container:{[Ye.variable]:"colors.chakra-subtle-bg"}}),unstyled:{body:{[R.variable]:0},header:{[R.variable]:0},footer:{[R.variable]:0}}},Gs=Ls({baseStyle:qs,variants:Ns,sizes:Os,defaultProps:{variant:"elevated",size:"md"}}),me=m("close-button-size"),ie=m("close-button-bg"),Us=t({w:[me.reference],h:[me.reference],borderRadius:"md",transitionProperty:"common",transitionDuration:"normal",_disabled:{opacity:.4,cursor:"not-allowed",boxShadow:"none"},_hover:{[ie.variable]:"colors.blackAlpha.100",_dark:{[ie.variable]:"colors.whiteAlpha.100"}},_active:{[ie.variable]:"colors.blackAlpha.200",_dark:{[ie.variable]:"colors.whiteAlpha.200"}},_focusVisible:{boxShadow:"outline"},bg:ie.reference}),Ys={lg:t({[me.variable]:"sizes.10",fontSize:"md"}),md:t({[me.variable]:"sizes.8",fontSize:"xs"}),sm:t({[me.variable]:"sizes.6",fontSize:"2xs"})},Xs=h({baseStyle:Us,sizes:Ys,defaultProps:{size:"md"}}),{variants:Ks,defaultProps:Zs}=ue,Js=t({fontFamily:"mono",fontSize:"sm",px:"0.2em",borderRadius:"sm",bg:y.bg.reference,color:y.color.reference,boxShadow:y.shadow.reference}),Qs=h({baseStyle:Js,variants:Ks,defaultProps:Zs}),e0=t({w:"100%",mx:"auto",maxW:"prose",px:"4"}),r0=h({baseStyle:e0}),a0=t({opacity:.6,borderColor:"inherit"}),t0=t({borderStyle:"solid"}),o0=t({borderStyle:"dashed"}),n0={solid:t0,dashed:o0},i0=h({baseStyle:a0,variants:n0,defaultProps:{variant:"solid"}}),{definePartsStyle:l0,defineMultiStyleConfig:s0}=b(Lt.keys),d0=t({borderTopWidth:"1px",borderColor:"inherit",_last:{borderBottomWidth:"1px"}}),c0=t({transitionProperty:"common",transitionDuration:"normal",fontSize:"md",_focusVisible:{boxShadow:"outline"},_hover:{bg:"blackAlpha.50"},_disabled:{opacity:.4,cursor:"not-allowed"},px:"4",py:"2"}),b0=t({pt:"2",px:"4",pb:"5"}),v0=t({fontSize:"1.25em"}),u0=l0({container:d0,button:c0,panel:b0,icon:v0}),f0=s0({baseStyle:u0}),{definePartsStyle:xe,defineMultiStyleConfig:m0}=b(qt.keys),w=c("alert-fg"),j=c("alert-bg"),h0=xe({container:{bg:j.reference,px:"4",py:"3"},title:{fontWeight:"bold",lineHeight:"6",marginEnd:"2"},description:{lineHeight:"6"},icon:{color:w.reference,flexShrink:0,marginEnd:"3",w:"5",h:"6"},spinner:{color:w.reference,flexShrink:0,marginEnd:"3",w:"5",h:"5"}});function _r(e){const{theme:r,colorScheme:a}=e,o=re(`${a}.200`,.16)(r);return{light:`colors.${a}.100`,dark:o}}var g0=xe(e=>{const{colorScheme:r}=e,a=_r(e);return{container:{[w.variable]:`colors.${r}.500`,[j.variable]:a.light,_dark:{[w.variable]:`colors.${r}.200`,[j.variable]:a.dark}}}}),y0=xe(e=>{const{colorScheme:r}=e,a=_r(e);return{container:{[w.variable]:`colors.${r}.500`,[j.variable]:a.light,_dark:{[w.variable]:`colors.${r}.200`,[j.variable]:a.dark},paddingStart:"3",borderStartWidth:"4px",borderStartColor:w.reference}}}),p0=xe(e=>{const{colorScheme:r}=e,a=_r(e);return{container:{[w.variable]:`colors.${r}.500`,[j.variable]:a.light,_dark:{[w.variable]:`colors.${r}.200`,[j.variable]:a.dark},pt:"2",borderTopWidth:"4px",borderTopColor:w.reference}}}),S0=xe(e=>{const{colorScheme:r}=e;return{container:{[w.variable]:"colors.white",[j.variable]:`colors.${r}.500`,_dark:{[w.variable]:"colors.gray.900",[j.variable]:`colors.${r}.200`},color:w.reference}}}),x0={subtle:g0,"left-accent":y0,"top-accent":p0,solid:S0},$0=m0({baseStyle:h0,variants:x0,defaultProps:{variant:"subtle",colorScheme:"blue"}}),{definePartsStyle:Aa,defineMultiStyleConfig:k0}=b(Ot.keys),ee=c("avatar-border-color"),he=c("avatar-bg"),Se=c("avatar-font-size"),ae=c("avatar-size"),_0=t({borderRadius:"full",border:"0.2em solid",borderColor:ee.reference,[ee.variable]:"white",_dark:{[ee.variable]:"colors.gray.800"}}),w0=t({bg:he.reference,fontSize:Se.reference,width:ae.reference,height:ae.reference,lineHeight:"1",[he.variable]:"colors.gray.200",_dark:{[he.variable]:"colors.whiteAlpha.400"}}),z0=t(e=>{const{name:r,theme:a}=e,o=r?Mo({string:r}):"colors.gray.400",i=Fo(o)(a);let l="white";return i||(l="gray.800"),{bg:he.reference,fontSize:Se.reference,color:l,borderColor:ee.reference,verticalAlign:"top",width:ae.reference,height:ae.reference,"&:not([data-loaded])":{[he.variable]:o},[ee.variable]:"colors.white",_dark:{[ee.variable]:"colors.gray.800"}}}),C0=t({fontSize:Se.reference,lineHeight:"1"}),A0=Aa(e=>({badge:k(_0,e),excessLabel:k(w0,e),container:k(z0,e),label:C0}));function W(e){const r=e!=="100%"?ya[e]:void 0;return Aa({container:{[ae.variable]:r??e,[Se.variable]:`calc(${r??e} / 2.5)`},excessLabel:{[ae.variable]:r??e,[Se.variable]:`calc(${r??e} / 2.5)`}})}var P0={"2xs":W(4),xs:W(6),sm:W(8),md:W(12),lg:W(16),xl:W(24),"2xl":W(32),full:W("100%")},T0=k0({baseStyle:A0,sizes:P0,defaultProps:{size:"md"}}),F0={Accordion:f0,Alert:$0,Avatar:T0,Badge:ue,Breadcrumb:Is,Button:Vs,Checkbox:Ue,CloseButton:Xs,Code:Qs,Container:r0,Divider:i0,Drawer:ts,Editable:cs,Form:hs,FormError:$s,FormLabel:_s,Heading:Cs,Input:u,Kbd:Yi,Link:Ki,List:rl,Menu:bl,Modal:$l,NumberInput:Fl,PinInput:El,Popover:Gl,Progress:ei,Radio:ui,Select:Si,Skeleton:$i,SkipLink:_i,Slider:Ei,Spinner:ji,Stat:Gi,Switch:Xo,Table:an,Tabs:yn,Tag:Fn,Textarea:qn,Tooltip:Gn,Card:Gs,Stepper:Vt},I0={colors:{"chakra-body-text":{_light:"gray.800",_dark:"whiteAlpha.900"},"chakra-body-bg":{_light:"white",_dark:"gray.800"},"chakra-border-color":{_light:"gray.200",_dark:"whiteAlpha.300"},"chakra-inverse-text":{_light:"white",_dark:"gray.800"},"chakra-subtle-bg":{_light:"gray.100",_dark:"gray.700"},"chakra-subtle-text":{_light:"gray.600",_dark:"gray.400"},"chakra-placeholder-color":{_light:"gray.500",_dark:"whiteAlpha.400"}}},M0={global:{body:{fontFamily:"body",color:"chakra-body-text",bg:"chakra-body-bg",transitionProperty:"background-color",transitionDuration:"normal",lineHeight:"base"},"*::placeholder":{color:"chakra-placeholder-color"},"*, *::before, &::after":{borderColor:"chakra-border-color"}}},B0="ltr",E0={useSystemColorMode:!1,initialColorMode:"light",cssVarPrefix:"chakra"},Pa={semanticTokens:I0,direction:B0,...jt,components:F0,styles:M0,config:E0};function be(e){return typeof e=="function"}function D0(...e){return r=>e.reduce((a,o)=>o(a),r)}var R0=e=>function(...a){let o=[...a],i=a[a.length-1];return ft(i)&&o.length>1?o=o.slice(0,o.length-1):i=e,D0(...o.map(l=>s=>be(l)?l(s):H0(s,l)))(i)},j0=R0(Pa);function H0(...e){return ba({},...e,Ta)}function Ta(e,r,a,o){if((be(e)||be(r))&&Object.prototype.hasOwnProperty.call(o,a))return(...i)=>{const l=be(e)?e(...i):e,s=be(r)?r(...i):r;return ba({},l,s,Ta)}}function W0(e={}){const{strict:r=!0,errorMessage:a="useContext: `context` is undefined. Seems you forgot to wrap component within the Provider",name:o}=e,i=x.createContext(void 0);i.displayName=o;function l(){var s;const d=x.useContext(i);if(!d&&r){const v=new Error(a);throw v.name="ContextError",(s=Error.captureStackTrace)==null||s.call(Error,v,l),v}return d}return[i.Provider,l,i]}function V0(e){const{cssVarsRoot:r,theme:a,children:o}=e,i=x.useMemo(()=>ja(a),[a]);return g.jsxs(Ha,{theme:i,children:[g.jsx(L0,{root:r}),o]})}function L0({root:e=":host, :root"}){const r=[e,"[data-theme]"].join(",");return g.jsx(Xe,{styles:a=>({[r]:a.__cssVars})})}W0({name:"StylesContext",errorMessage:"useStyles: `styles` is undefined. Seems you forgot to wrap the components in `` "});function q0(){const{colorMode:e}=Wa();return g.jsx(Xe,{styles:r=>{const a=Va(r,"styles.global"),o=La(a,{theme:r,colorMode:e});return o?qa(o)(r):void 0}})}var Fa=x.createContext({getDocument(){return document},getWindow(){return window}});Fa.displayName="EnvironmentContext";function Ia(e){const{children:r,environment:a,disabled:o}=e,i=x.useRef(null),l=x.useMemo(()=>a||{getDocument:()=>{var d,v;return(v=(d=i.current)==null?void 0:d.ownerDocument)!=null?v:document},getWindow:()=>{var d,v;return(v=(d=i.current)==null?void 0:d.ownerDocument.defaultView)!=null?v:window}},[a]),s=!o||!a;return g.jsxs(Fa.Provider,{value:l,children:[r,s&&g.jsx("span",{id:"__chakra_env",hidden:!0,ref:i})]})}Ia.displayName="EnvironmentProvider";var O0=e=>{const{children:r,colorModeManager:a,portalZIndex:o,resetScope:i,resetCSS:l=!0,theme:s={},environment:d,cssVarsRoot:v,disableEnvironment:$,disableGlobalStyle:p}=e,S=g.jsx(Ia,{environment:d,disabled:$,children:r});return g.jsx(V0,{theme:s,cssVarsRoot:v,children:g.jsxs(ma,{colorModeManager:a,options:s.config,children:[l?g.jsx(dt,{scope:i}):g.jsx(st,{}),!p&&g.jsx(q0,{}),o?g.jsx(Oa,{zIndex:o,children:S}):S]})})},N0=e=>function({children:a,theme:o=e,toastOptions:i,...l}){return g.jsxs(O0,{theme:o,...l,children:[g.jsx(Na,{value:i==null?void 0:i.defaultOptions,children:a}),g.jsx(Ga,{...i})]})},G0=N0(Pa);function z(e,r,a=!1){e=String(e),r=String(r);const o=Array.from({length:21},(s,d)=>d*50),i=[0,5,10,15,20,25,30,35,40,45,50,55,59,64,68,73,77,82,86,95,100];return o.reduce((s,d,v)=>{const $=a?i[v]/100:1,p=a?50:i[o.length-1-v];return s[d]=`hsl(${e} ${r}% ${p}% / ${$})`,s},{})}const Fe={H:220,S:16},Ie={H:250,S:42},Me={H:47,S:42},Be={H:28,S:42},Ee={H:113,S:42},De={H:0,S:42},U0={base:z(Fe.H,Fe.S),baseAlpha:z(Fe.H,Fe.S,!0),accent:z(Ie.H,Ie.S),accentAlpha:z(Ie.H,Ie.S,!0),working:z(Me.H,Me.S),workingAlpha:z(Me.H,Me.S,!0),warning:z(Be.H,Be.S),warningAlpha:z(Be.H,Be.S,!0),ok:z(Ee.H,Ee.S),okAlpha:z(Ee.H,Ee.S,!0),error:z(De.H,De.S),errorAlpha:z(De.H,De.S,!0)},{definePartsStyle:Y0,defineMultiStyleConfig:X0}=b(Ua.keys),K0=t({border:"none"}),Z0=t(e=>{const{colorScheme:r}=e;return{fontWeight:"600",fontSize:"sm",border:"none",borderRadius:"base",bg:n(`${r}.200`,`${r}.700`)(e),color:n(`${r}.900`,`${r}.100`)(e),_hover:{bg:n(`${r}.250`,`${r}.650`)(e)},_expanded:{bg:n(`${r}.250`,`${r}.650`)(e),borderBottomRadius:"none",_hover:{bg:n(`${r}.300`,`${r}.600`)(e)}}}}),J0=t(e=>{const{colorScheme:r}=e;return{bg:n(`${r}.100`,`${r}.800`)(e),borderRadius:"base",borderTopRadius:"none"}}),Q0=t({}),ed=Y0(e=>({container:K0,button:Z0(e),panel:J0(e),icon:Q0})),rd=X0({variants:{invokeAI:ed},defaultProps:{variant:"invokeAI",colorScheme:"base"}}),ad=t(e=>{const{colorScheme:r}=e;if(r==="base"){const o={bg:n("base.150","base.700")(e),color:n("base.500","base.500")(e),svg:{fill:n("base.500","base.500")(e)},opacity:1};return{bg:n("base.250","base.600")(e),color:n("base.850","base.100")(e),borderRadius:"base",svg:{fill:n("base.850","base.100")(e)},_hover:{bg:n("base.300","base.500")(e),color:n("base.900","base.50")(e),svg:{fill:n("base.900","base.50")(e)},_disabled:o},_disabled:o}}const a={bg:n(`${r}.250`,`${r}.700`)(e),color:n(`${r}.50`,`${r}.500`)(e),svg:{fill:n(`${r}.50`,`${r}.500`)(e),filter:"unset"},opacity:1,filter:n(void 0,"saturate(65%)")(e)};return{bg:n(`${r}.400`,`${r}.600`)(e),color:n("base.50","base.100")(e),borderRadius:"base",svg:{fill:n("base.50","base.100")(e)},_disabled:a,_hover:{bg:n(`${r}.500`,`${r}.500`)(e),color:n("white","base.50")(e),svg:{fill:n("white","base.50")(e)},_disabled:a}}}),td=t(e=>{const{colorScheme:r}=e,a=n("gray.200","whiteAlpha.300")(e);return{border:"1px solid",borderColor:r==="gray"?a:"currentColor",".chakra-button__group[data-attached][data-orientation=horizontal] > &:not(:last-of-type)":{marginEnd:"-1px"},".chakra-button__group[data-attached][data-orientation=vertical] > &:not(:last-of-type)":{marginBottom:"-1px"}}}),od=h({variants:{invokeAI:ad,invokeAIOutline:td},defaultProps:{variant:"invokeAI",colorScheme:"base"}}),{definePartsStyle:nd,defineMultiStyleConfig:id}=b(Ya.keys),ld=t(e=>{const{colorScheme:r}=e;return{bg:n("base.200","base.700")(e),borderColor:n("base.200","base.700")(e),color:n("base.900","base.100")(e),_checked:{bg:n(`${r}.300`,`${r}.600`)(e),borderColor:n(`${r}.300`,`${r}.600`)(e),color:n(`${r}.900`,`${r}.100`)(e),_hover:{bg:n(`${r}.400`,`${r}.500`)(e),borderColor:n(`${r}.400`,`${r}.500`)(e)},_disabled:{borderColor:"transparent",bg:"whiteAlpha.300",color:"whiteAlpha.500"}},_indeterminate:{bg:n(`${r}.300`,`${r}.600`)(e),borderColor:n(`${r}.300`,`${r}.600`)(e),color:n(`${r}.900`,`${r}.100`)(e)},_disabled:{bg:"whiteAlpha.100",borderColor:"transparent"},_focusVisible:{boxShadow:"outline"},_invalid:{borderColor:n("error.600","error.300")(e)}}}),sd=nd(e=>({control:ld(e)})),dd=id({variants:{invokeAI:sd},defaultProps:{variant:"invokeAI",colorScheme:"accent"}}),{definePartsStyle:cd,defineMultiStyleConfig:bd}=b(Xa.keys),vd=t({borderRadius:"md",py:"1",transitionProperty:"common",transitionDuration:"normal"}),ud=t(e=>({borderRadius:"md",py:"1",transitionProperty:"common",transitionDuration:"normal",width:"full",_focusVisible:{boxShadow:"outline"},_placeholder:{opacity:.6},"::selection":{color:n("accent.900","accent.50")(e),bg:n("accent.200","accent.400")(e)}})),fd=t({borderRadius:"md",py:"1",transitionProperty:"common",transitionDuration:"normal",width:"full",_focusVisible:{boxShadow:"outline"},_placeholder:{opacity:.6}}),md=cd(e=>({preview:vd,input:ud(e),textarea:fd})),hd=bd({variants:{invokeAI:md},defaultProps:{size:"sm",variant:"invokeAI"}}),gd=t(e=>({fontSize:"sm",marginEnd:0,mb:1,fontWeight:"400",transitionProperty:"common",transitionDuration:"normal",whiteSpace:"nowrap",_disabled:{opacity:.4},color:n("base.700","base.300")(e)})),yd=h({variants:{invokeAI:gd},defaultProps:{variant:"invokeAI"}}),Je=e=>({outline:"none",borderWidth:2,borderStyle:"solid",borderColor:n("base.200","base.800")(e),bg:n("base.50","base.900")(e),borderRadius:"base",color:n("base.900","base.100")(e),boxShadow:"none",_hover:{borderColor:n("base.300","base.600")(e)},_focus:{borderColor:n("accent.200","accent.600")(e),boxShadow:"none",_hover:{borderColor:n("accent.300","accent.500")(e)}},_invalid:{borderColor:n("error.300","error.600")(e),boxShadow:"none",_hover:{borderColor:n("error.400","error.500")(e)}},_disabled:{borderColor:n("base.300","base.700")(e),bg:n("base.300","base.700")(e),color:n("base.600","base.400")(e),_hover:{borderColor:n("base.300","base.700")(e)}},_placeholder:{color:n("base.700","base.400")(e)},"::selection":{bg:n("accent.200","accent.400")(e)}}),{definePartsStyle:pd,defineMultiStyleConfig:Sd}=b(Ka.keys),xd=pd(e=>({field:Je(e)})),$d=Sd({variants:{invokeAI:xd},defaultProps:{size:"sm",variant:"invokeAI"}}),{defineMultiStyleConfig:kd,definePartsStyle:_d}=b(Za.keys),wd=t(e=>({bg:n("blackAlpha.700","blackAlpha.700")(e)})),zd=t({}),Cd=t(()=>({layerStyle:"first",maxH:"80vh"})),Ad=t(()=>({fontWeight:"600",fontSize:"lg",layerStyle:"first",borderTopRadius:"base",borderInlineEndRadius:"base"})),Pd=t({}),Td=t({overflowY:"scroll"}),Fd=t({}),Id=_d(e=>({overlay:wd(e),dialogContainer:zd,dialog:Cd(),header:Ad(),closeButton:Pd,body:Td,footer:Fd})),Md=kd({variants:{invokeAI:Id},defaultProps:{variant:"invokeAI",size:"lg"}}),{defineMultiStyleConfig:Bd,definePartsStyle:Ed}=b(Ja.keys),Dd=t(e=>({height:8})),Rd=t(e=>({border:"none",fontWeight:"600",height:"auto",py:1,ps:2,pe:6,...Je(e)})),jd=t(e=>({display:"flex"})),Hd=t(e=>({border:"none",px:2,py:0,mx:-2,my:0,svg:{color:n("base.700","base.300")(e),width:2.5,height:2.5,_hover:{color:n("base.900","base.100")(e)}}})),Wd=Ed(e=>({root:Dd(e),field:Rd(e),stepperGroup:jd(e),stepper:Hd(e)})),Vd=Bd({variants:{invokeAI:Wd},defaultProps:{size:"sm",variant:"invokeAI"}}),{defineMultiStyleConfig:Ld,definePartsStyle:qd}=b(Qa.keys),Od=m("popper-bg"),Nd=m("popper-arrow-bg"),Gd=m("popper-arrow-shadow-color"),Ud=t(e=>({[Nd.variable]:n("colors.base.100","colors.base.800")(e),[Od.variable]:n("colors.base.100","colors.base.800")(e),[Gd.variable]:n("colors.base.400","colors.base.600")(e),minW:"unset",width:"unset",p:4,bg:n("base.100","base.800")(e),border:"none",shadow:"dark-lg"})),Yd=qd(e=>({content:Ud(e)})),Xd=Ld({variants:{invokeAI:Yd},defaultProps:{variant:"invokeAI"}}),{defineMultiStyleConfig:Kd,definePartsStyle:Zd}=b(et.keys),Jd=t(e=>({bg:"accentAlpha.500"})),Qd=t(e=>{const{colorScheme:r}=e;return{bg:n(`${r}.200`,`${r}.700`)(e)}}),ec=Zd(e=>({filledTrack:Jd(e),track:Qd(e)})),rc=Kd({variants:{invokeAI:ec},defaultProps:{variant:"invokeAI"}}),ac={"::-webkit-scrollbar":{display:"none"},scrollbarWidth:"none"},{definePartsStyle:tc,defineMultiStyleConfig:oc}=b(rt.keys),nc=t(e=>({color:n("base.200","base.300")(e)})),ic=t(e=>({fontWeight:"600",...Je(e)})),lc=tc(e=>({field:ic(e),icon:nc(e)})),sc=oc({variants:{invokeAI:lc},defaultProps:{size:"sm",variant:"invokeAI"}}),sa=c("skeleton-start-color"),da=c("skeleton-end-color"),dc=t({borderRadius:"base",maxW:"full",maxH:"full",_light:{[sa.variable]:"colors.base.250",[da.variable]:"colors.base.450"},_dark:{[sa.variable]:"colors.base.700",[da.variable]:"colors.base.500"}}),cc=h({variants:{invokeAI:dc},defaultProps:{variant:"invokeAI"}}),{definePartsStyle:bc,defineMultiStyleConfig:vc}=b(at.keys),uc=t(e=>({bg:n("base.400","base.600")(e),h:1.5})),fc=t(e=>{const{colorScheme:r}=e;return{bg:n(`${r}.400`,`${r}.600`)(e),h:1.5}}),mc=t(e=>({w:2,h:4,bg:n("base.50","base.100")(e)})),hc=t(e=>({fontSize:"2xs",fontWeight:"500",color:n("base.700","base.400")(e),mt:2,insetInlineStart:"unset"})),gc=bc(e=>({container:{_disabled:{opacity:.6,cursor:"default",pointerEvents:"none"}},track:uc(e),filledTrack:fc(e),thumb:mc(e),mark:hc(e)})),yc=vc({variants:{invokeAI:gc},defaultProps:{variant:"invokeAI",colorScheme:"accent"}}),{defineMultiStyleConfig:pc,definePartsStyle:Sc}=b(tt.keys),xc=t(e=>{const{colorScheme:r}=e;return{bg:n("base.300","base.600")(e),_focusVisible:{boxShadow:"none"},_checked:{bg:n(`${r}.400`,`${r}.500`)(e)}}}),$c=t(e=>{const{colorScheme:r}=e;return{bg:n(`${r}.50`,`${r}.50`)(e)}}),kc=Sc(e=>({container:{},track:xc(e),thumb:$c(e)})),_c=pc({variants:{invokeAI:kc},defaultProps:{size:"md",variant:"invokeAI",colorScheme:"accent"}}),{defineMultiStyleConfig:wc,definePartsStyle:zc}=b(ot.keys),Cc=t(e=>({display:"flex",columnGap:4})),Ac=t(e=>({})),Pc=t(e=>{const{colorScheme:r}=e;return{display:"flex",flexDirection:"column",gap:1,color:n("base.700","base.400")(e),button:{fontSize:"sm",padding:2,borderRadius:"base",textShadow:n("0 0 0.3rem var(--invokeai-colors-accent-100)","0 0 0.3rem var(--invokeai-colors-accent-900)")(e),svg:{fill:n("base.700","base.300")(e)},_selected:{bg:n("accent.400","accent.600")(e),color:n("base.50","base.100")(e),svg:{fill:n("base.50","base.100")(e),filter:n(`drop-shadow(0px 0px 0.3rem var(--invokeai-colors-${r}-600))`,`drop-shadow(0px 0px 0.3rem var(--invokeai-colors-${r}-800))`)(e)},_hover:{bg:n("accent.500","accent.500")(e),color:n("white","base.50")(e),svg:{fill:n("white","base.50")(e)}}},_hover:{bg:n("base.100","base.800")(e),color:n("base.900","base.50")(e),svg:{fill:n("base.800","base.100")(e)}}}}}),Tc=t(e=>({padding:0,height:"100%"})),Fc=zc(e=>({root:Cc(e),tab:Ac(e),tablist:Pc(e),tabpanel:Tc(e)})),Ic=wc({variants:{invokeAI:Fc},defaultProps:{variant:"invokeAI",colorScheme:"accent"}}),Mc=t(e=>({color:n("base.500","base.400")(e)})),Bc=h({variants:{subtext:Mc}}),Ec=t(e=>({...Je(e),"::-webkit-scrollbar":{display:"initial"},"::-webkit-resizer":{backgroundImage:`linear-gradient(135deg, + var(--invokeai-colors-base-50) 0%, + var(--invokeai-colors-base-50) 70%, + var(--invokeai-colors-base-200) 70%, + var(--invokeai-colors-base-200) 100%)`},_dark:{"::-webkit-resizer":{backgroundImage:`linear-gradient(135deg, + var(--invokeai-colors-base-900) 0%, + var(--invokeai-colors-base-900) 70%, + var(--invokeai-colors-base-800) 70%, + var(--invokeai-colors-base-800) 100%)`}}})),Dc=h({variants:{invokeAI:Ec},defaultProps:{size:"md",variant:"invokeAI"}}),Rc=m("popper-arrow-bg"),jc=t(e=>({borderRadius:"base",shadow:"dark-lg",bg:n("base.700","base.200")(e),[Rc.variable]:n("colors.base.700","colors.base.200")(e),pb:1.5})),Hc=h({baseStyle:jc}),Wc={config:{cssVarPrefix:"invokeai",initialColorMode:"dark",useSystemColorMode:!1},layerStyles:{body:{bg:"base.50",color:"base.900",".chakra-ui-dark &":{bg:"base.900",color:"base.50"}},first:{bg:"base.100",color:"base.900",".chakra-ui-dark &":{bg:"base.850",color:"base.100"}},second:{bg:"base.200",color:"base.900",".chakra-ui-dark &":{bg:"base.800",color:"base.100"}}},styles:{global:()=>({layerStyle:"body","*":{...ac}})},direction:"ltr",fonts:{body:"'Inter Variable', sans-serif"},shadows:{light:{accent:"0 0 10px 0 var(--invokeai-colors-accent-300)",accentHover:"0 0 10px 0 var(--invokeai-colors-accent-400)",ok:"0 0 7px var(--invokeai-colors-ok-600)",working:"0 0 7px var(--invokeai-colors-working-600)",error:"0 0 7px var(--invokeai-colors-error-600)"},dark:{accent:"0 0 10px 0 var(--invokeai-colors-accent-600)",accentHover:"0 0 10px 0 var(--invokeai-colors-accent-500)",ok:"0 0 7px var(--invokeai-colors-ok-400)",working:"0 0 7px var(--invokeai-colors-working-400)",error:"0 0 7px var(--invokeai-colors-error-400)"},selected:{light:"0px 0px 0px 1px var(--invokeai-colors-base-150), 0px 0px 0px 4px var(--invokeai-colors-accent-400)",dark:"0px 0px 0px 1px var(--invokeai-colors-base-900), 0px 0px 0px 4px var(--invokeai-colors-accent-500)"},hoverSelected:{light:"0px 0px 0px 1px var(--invokeai-colors-base-150), 0px 0px 0px 4px var(--invokeai-colors-accent-500)",dark:"0px 0px 0px 1px var(--invokeai-colors-base-900), 0px 0px 0px 4px var(--invokeai-colors-accent-400)"},hoverUnselected:{light:"0px 0px 0px 1px var(--invokeai-colors-base-150), 0px 0px 0px 3px var(--invokeai-colors-accent-500)",dark:"0px 0px 0px 1px var(--invokeai-colors-base-900), 0px 0px 0px 3px var(--invokeai-colors-accent-400)"},nodeSelectedOutline:"0 0 0 2px var(--invokeai-colors-accent-450)"},colors:U0,components:{Button:od,Input:$d,Editable:hd,Textarea:Dc,Tabs:Ic,Progress:rc,Accordion:rd,FormLabel:yd,Switch:_c,NumberInput:Vd,Select:sc,Skeleton:cc,Slider:yc,Popover:Xd,Modal:Md,Checkbox:dd,Menu:nt,Text:Bc,Tooltip:Hc}};const Vc=()=>x.useMemo(()=>({colorScheme:"dark",fontFamily:"'Inter Variable', sans-serif",components:{ScrollArea:{defaultProps:{scrollbarSize:10},styles:{scrollbar:{"&:hover":{backgroundColor:"var(--invokeai-colors-baseAlpha-300)"}},thumb:{backgroundColor:"var(--invokeai-colors-baseAlpha-300)"}}}}}),[]),Lc=fa("@@invokeai-color-mode");function Nc({children:e}){const{i18n:r}=it(),a=r.dir(),o=x.useMemo(()=>j0({...Wc,direction:a}),[a]);x.useEffect(()=>{document.body.dir=a},[a]);const i=Vc();return g.jsx(lt,{theme:i,children:g.jsx(G0,{theme:o,colorModeManager:Lc,children:e})})}export{Nc as default}; diff --git a/invokeai/frontend/web/dist/assets/index-89941396.js b/invokeai/frontend/web/dist/assets/index-89941396.js new file mode 100644 index 0000000000..af6430d8cd --- /dev/null +++ b/invokeai/frontend/web/dist/assets/index-89941396.js @@ -0,0 +1,125 @@ +function O8(e,t){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(i){if(i.ep)return;i.ep=!0;const o=n(i);fetch(i.href,o)}})();var Ee=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function al(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function nF(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var n=function r(){if(this instanceof r){var i=[null];i.push.apply(i,arguments);var o=Function.bind.apply(t,i);return new o}return t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}),n}var R8={exports:{}},Sy={},I8={exports:{}},Re={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Jf=Symbol.for("react.element"),rF=Symbol.for("react.portal"),iF=Symbol.for("react.fragment"),oF=Symbol.for("react.strict_mode"),sF=Symbol.for("react.profiler"),aF=Symbol.for("react.provider"),lF=Symbol.for("react.context"),uF=Symbol.for("react.forward_ref"),cF=Symbol.for("react.suspense"),dF=Symbol.for("react.memo"),fF=Symbol.for("react.lazy"),N3=Symbol.iterator;function hF(e){return e===null||typeof e!="object"?null:(e=N3&&e[N3]||e["@@iterator"],typeof e=="function"?e:null)}var M8={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},N8=Object.assign,D8={};function dc(e,t,n){this.props=e,this.context=t,this.refs=D8,this.updater=n||M8}dc.prototype.isReactComponent={};dc.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};dc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function L8(){}L8.prototype=dc.prototype;function lw(e,t,n){this.props=e,this.context=t,this.refs=D8,this.updater=n||M8}var uw=lw.prototype=new L8;uw.constructor=lw;N8(uw,dc.prototype);uw.isPureReactComponent=!0;var D3=Array.isArray,$8=Object.prototype.hasOwnProperty,cw={current:null},F8={key:!0,ref:!0,__self:!0,__source:!0};function B8(e,t,n){var r,i={},o=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(o=""+t.key),t)$8.call(t,r)&&!F8.hasOwnProperty(r)&&(i[r]=t[r]);var a=arguments.length-2;if(a===1)i.children=n;else if(1>>1,U=R[j];if(0>>1;ji(X,L))Yi(B,X)?(R[j]=B,R[Y]=L,j=Y):(R[j]=X,R[W]=L,j=W);else if(Yi(B,L))R[j]=B,R[Y]=L,j=Y;else break e}}return D}function i(R,D){var L=R.sortIndex-D.sortIndex;return L!==0?L:R.id-D.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var s=Date,a=s.now();e.unstable_now=function(){return s.now()-a}}var l=[],u=[],c=1,d=null,f=3,h=!1,p=!1,m=!1,S=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,y=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function g(R){for(var D=n(u);D!==null;){if(D.callback===null)r(u);else if(D.startTime<=R)r(u),D.sortIndex=D.expirationTime,t(l,D);else break;D=n(u)}}function b(R){if(m=!1,g(R),!p)if(n(l)!==null)p=!0,I(_);else{var D=n(u);D!==null&&N(b,D.startTime-R)}}function _(R,D){p=!1,m&&(m=!1,v(T),T=-1),h=!0;var L=f;try{for(g(D),d=n(l);d!==null&&(!(d.expirationTime>D)||R&&!A());){var j=d.callback;if(typeof j=="function"){d.callback=null,f=d.priorityLevel;var U=j(d.expirationTime<=D);D=e.unstable_now(),typeof U=="function"?d.callback=U:d===n(l)&&r(l),g(D)}else r(l);d=n(l)}if(d!==null)var G=!0;else{var W=n(u);W!==null&&N(b,W.startTime-D),G=!1}return G}finally{d=null,f=L,h=!1}}var w=!1,x=null,T=-1,P=5,E=-1;function A(){return!(e.unstable_now()-ER||125j?(R.sortIndex=L,t(u,R),n(l)===null&&R===n(u)&&(m?(v(T),T=-1):m=!0,N(b,L-j))):(R.sortIndex=U,t(l,R),p||h||(p=!0,I(_))),R},e.unstable_shouldYield=A,e.unstable_wrapCallback=function(R){var D=f;return function(){var L=f;f=D;try{return R.apply(this,arguments)}finally{f=L}}}})(U8);z8.exports=U8;var CF=z8.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var G8=k,kr=CF;function Z(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),CS=Object.prototype.hasOwnProperty,TF=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,F3={},B3={};function EF(e){return CS.call(B3,e)?!0:CS.call(F3,e)?!1:TF.test(e)?B3[e]=!0:(F3[e]=!0,!1)}function PF(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function AF(e,t,n,r){if(t===null||typeof t>"u"||PF(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function rr(e,t,n,r,i,o,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=s}var kn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){kn[e]=new rr(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];kn[t]=new rr(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){kn[e]=new rr(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){kn[e]=new rr(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){kn[e]=new rr(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){kn[e]=new rr(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){kn[e]=new rr(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){kn[e]=new rr(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){kn[e]=new rr(e,5,!1,e.toLowerCase(),null,!1,!1)});var fw=/[\-:]([a-z])/g;function hw(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(fw,hw);kn[t]=new rr(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(fw,hw);kn[t]=new rr(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(fw,hw);kn[t]=new rr(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){kn[e]=new rr(e,1,!1,e.toLowerCase(),null,!1,!1)});kn.xlinkHref=new rr("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){kn[e]=new rr(e,1,!1,e.toLowerCase(),null,!0,!0)});function pw(e,t,n,r){var i=kn.hasOwnProperty(t)?kn[t]:null;(i!==null?i.type!==0:r||!(2a||i[s]!==o[a]){var l=` +`+i[s].replace(" at new "," at ");return e.displayName&&l.includes("")&&(l=l.replace("",e.displayName)),l}while(1<=s&&0<=a);break}}}finally{D1=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?ad(e):""}function kF(e){switch(e.tag){case 5:return ad(e.type);case 16:return ad("Lazy");case 13:return ad("Suspense");case 19:return ad("SuspenseList");case 0:case 2:case 15:return e=L1(e.type,!1),e;case 11:return e=L1(e.type.render,!1),e;case 1:return e=L1(e.type,!0),e;default:return""}}function AS(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case eu:return"Fragment";case Jl:return"Portal";case TS:return"Profiler";case gw:return"StrictMode";case ES:return"Suspense";case PS:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case W8:return(e.displayName||"Context")+".Consumer";case q8:return(e._context.displayName||"Context")+".Provider";case mw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case yw:return t=e.displayName||null,t!==null?t:AS(e.type)||"Memo";case ls:t=e._payload,e=e._init;try{return AS(e(t))}catch{}}return null}function OF(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return AS(t);case 8:return t===gw?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Ls(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function X8(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function RF(e){var t=X8(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var i=n.get,o=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(s){r=""+s,o.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Qh(e){e._valueTracker||(e._valueTracker=RF(e))}function Y8(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=X8(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Mg(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function kS(e,t){var n=t.checked;return Ot({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function V3(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ls(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Q8(e,t){t=t.checked,t!=null&&pw(e,"checked",t,!1)}function OS(e,t){Q8(e,t);var n=Ls(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?RS(e,t.type,n):t.hasOwnProperty("defaultValue")&&RS(e,t.type,Ls(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function z3(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function RS(e,t,n){(t!=="number"||Mg(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var ld=Array.isArray;function yu(e,t,n,r){if(e=e.options,t){t={};for(var i=0;i"+t.valueOf().toString()+"",t=Zh.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Bd(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var yd={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},IF=["Webkit","ms","Moz","O"];Object.keys(yd).forEach(function(e){IF.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),yd[t]=yd[e]})});function tA(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||yd.hasOwnProperty(e)&&yd[e]?(""+t).trim():t+"px"}function nA(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,i=tA(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,i):e[n]=i}}var MF=Ot({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function NS(e,t){if(t){if(MF[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Z(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Z(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Z(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Z(62))}}function DS(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var LS=null;function vw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var $S=null,vu=null,bu=null;function H3(e){if(e=nh(e)){if(typeof $S!="function")throw Error(Z(280));var t=e.stateNode;t&&(t=Ty(t),$S(e.stateNode,e.type,t))}}function rA(e){vu?bu?bu.push(e):bu=[e]:vu=e}function iA(){if(vu){var e=vu,t=bu;if(bu=vu=null,H3(e),t)for(e=0;e>>=0,e===0?32:31-(GF(e)/HF|0)|0}var Jh=64,ep=4194304;function ud(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function $g(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,i=e.suspendedLanes,o=e.pingedLanes,s=n&268435455;if(s!==0){var a=s&~i;a!==0?r=ud(a):(o&=s,o!==0&&(r=ud(o)))}else s=n&~i,s!==0?r=ud(s):o!==0&&(r=ud(o));if(r===0)return 0;if(t!==0&&t!==r&&!(t&i)&&(i=r&-r,o=t&-t,i>=o||i===16&&(o&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function eh(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-mi(t),e[t]=n}function XF(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=bd),e5=String.fromCharCode(32),t5=!1;function CA(e,t){switch(e){case"keyup":return xB.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function TA(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var tu=!1;function TB(e,t){switch(e){case"compositionend":return TA(t);case"keypress":return t.which!==32?null:(t5=!0,e5);case"textInput":return e=t.data,e===e5&&t5?null:e;default:return null}}function EB(e,t){if(tu)return e==="compositionend"||!Ew&&CA(e,t)?(e=wA(),eg=xw=vs=null,tu=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=o5(n)}}function kA(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?kA(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function OA(){for(var e=window,t=Mg();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Mg(e.document)}return t}function Pw(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function DB(e){var t=OA(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&kA(n.ownerDocument.documentElement,n)){if(r!==null&&Pw(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var i=n.textContent.length,o=Math.min(r.start,i);r=r.end===void 0?o:Math.min(r.end,i),!e.extend&&o>r&&(i=r,r=o,o=i),i=s5(n,o);var s=s5(n,r);i&&s&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(i.node,i.offset),e.removeAllRanges(),o>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,nu=null,US=null,_d=null,GS=!1;function a5(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;GS||nu==null||nu!==Mg(r)||(r=nu,"selectionStart"in r&&Pw(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),_d&&Hd(_d,r)||(_d=r,r=jg(US,"onSelect"),0ou||(e.current=YS[ou],YS[ou]=null,ou--)}function at(e,t){ou++,YS[ou]=e.current,e.current=t}var $s={},Bn=Qs($s),pr=Qs(!1),Ha=$s;function ju(e,t){var n=e.type.contextTypes;if(!n)return $s;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var i={},o;for(o in n)i[o]=t[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function gr(e){return e=e.childContextTypes,e!=null}function zg(){ht(pr),ht(Bn)}function p5(e,t,n){if(Bn.current!==$s)throw Error(Z(168));at(Bn,t),at(pr,n)}function BA(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var i in r)if(!(i in t))throw Error(Z(108,OF(e)||"Unknown",i));return Ot({},n,r)}function Ug(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||$s,Ha=Bn.current,at(Bn,e),at(pr,pr.current),!0}function g5(e,t,n){var r=e.stateNode;if(!r)throw Error(Z(169));n?(e=BA(e,t,Ha),r.__reactInternalMemoizedMergedChildContext=e,ht(pr),ht(Bn),at(Bn,e)):ht(pr),at(pr,n)}var _o=null,Ey=!1,Y1=!1;function jA(e){_o===null?_o=[e]:_o.push(e)}function WB(e){Ey=!0,jA(e)}function Zs(){if(!Y1&&_o!==null){Y1=!0;var e=0,t=Ke;try{var n=_o;for(Ke=1;e>=s,i-=s,To=1<<32-mi(t)+i|n<T?(P=x,x=null):P=x.sibling;var E=f(v,x,g[T],b);if(E===null){x===null&&(x=P);break}e&&x&&E.alternate===null&&t(v,x),y=o(E,y,T),w===null?_=E:w.sibling=E,w=E,x=P}if(T===g.length)return n(v,x),St&&Sa(v,T),_;if(x===null){for(;TT?(P=x,x=null):P=x.sibling;var A=f(v,x,E.value,b);if(A===null){x===null&&(x=P);break}e&&x&&A.alternate===null&&t(v,x),y=o(A,y,T),w===null?_=A:w.sibling=A,w=A,x=P}if(E.done)return n(v,x),St&&Sa(v,T),_;if(x===null){for(;!E.done;T++,E=g.next())E=d(v,E.value,b),E!==null&&(y=o(E,y,T),w===null?_=E:w.sibling=E,w=E);return St&&Sa(v,T),_}for(x=r(v,x);!E.done;T++,E=g.next())E=h(x,v,T,E.value,b),E!==null&&(e&&E.alternate!==null&&x.delete(E.key===null?T:E.key),y=o(E,y,T),w===null?_=E:w.sibling=E,w=E);return e&&x.forEach(function($){return t(v,$)}),St&&Sa(v,T),_}function S(v,y,g,b){if(typeof g=="object"&&g!==null&&g.type===eu&&g.key===null&&(g=g.props.children),typeof g=="object"&&g!==null){switch(g.$$typeof){case Yh:e:{for(var _=g.key,w=y;w!==null;){if(w.key===_){if(_=g.type,_===eu){if(w.tag===7){n(v,w.sibling),y=i(w,g.props.children),y.return=v,v=y;break e}}else if(w.elementType===_||typeof _=="object"&&_!==null&&_.$$typeof===ls&&w5(_)===w.type){n(v,w.sibling),y=i(w,g.props),y.ref=$c(v,w,g),y.return=v,v=y;break e}n(v,w);break}else t(v,w);w=w.sibling}g.type===eu?(y=$a(g.props.children,v.mode,b,g.key),y.return=v,v=y):(b=lg(g.type,g.key,g.props,null,v.mode,b),b.ref=$c(v,y,g),b.return=v,v=b)}return s(v);case Jl:e:{for(w=g.key;y!==null;){if(y.key===w)if(y.tag===4&&y.stateNode.containerInfo===g.containerInfo&&y.stateNode.implementation===g.implementation){n(v,y.sibling),y=i(y,g.children||[]),y.return=v,v=y;break e}else{n(v,y);break}else t(v,y);y=y.sibling}y=ib(g,v.mode,b),y.return=v,v=y}return s(v);case ls:return w=g._init,S(v,y,w(g._payload),b)}if(ld(g))return p(v,y,g,b);if(Ic(g))return m(v,y,g,b);ap(v,g)}return typeof g=="string"&&g!==""||typeof g=="number"?(g=""+g,y!==null&&y.tag===6?(n(v,y.sibling),y=i(y,g),y.return=v,v=y):(n(v,y),y=rb(g,v.mode,b),y.return=v,v=y),s(v)):n(v,y)}return S}var zu=KA(!0),XA=KA(!1),rh={},Xi=Qs(rh),Xd=Qs(rh),Yd=Qs(rh);function Oa(e){if(e===rh)throw Error(Z(174));return e}function Lw(e,t){switch(at(Yd,t),at(Xd,e),at(Xi,rh),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:MS(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=MS(t,e)}ht(Xi),at(Xi,t)}function Uu(){ht(Xi),ht(Xd),ht(Yd)}function YA(e){Oa(Yd.current);var t=Oa(Xi.current),n=MS(t,e.type);t!==n&&(at(Xd,e),at(Xi,n))}function $w(e){Xd.current===e&&(ht(Xi),ht(Xd))}var Et=Qs(0);function Xg(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var Q1=[];function Fw(){for(var e=0;en?n:4,e(!0);var r=Z1.transition;Z1.transition={};try{e(!1),t()}finally{Ke=n,Z1.transition=r}}function f9(){return Qr().memoizedState}function QB(e,t,n){var r=As(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},h9(e))p9(t,n);else if(n=GA(e,t,n,r),n!==null){var i=Zn();yi(n,e,r,i),g9(n,t,r)}}function ZB(e,t,n){var r=As(e),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(h9(e))p9(t,i);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var s=t.lastRenderedState,a=o(s,n);if(i.hasEagerState=!0,i.eagerState=a,wi(a,s)){var l=t.interleaved;l===null?(i.next=i,Nw(t)):(i.next=l.next,l.next=i),t.interleaved=i;return}}catch{}finally{}n=GA(e,t,i,r),n!==null&&(i=Zn(),yi(n,e,r,i),g9(n,t,r))}}function h9(e){var t=e.alternate;return e===kt||t!==null&&t===kt}function p9(e,t){wd=Yg=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function g9(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Sw(e,n)}}var Qg={readContext:Yr,useCallback:Mn,useContext:Mn,useEffect:Mn,useImperativeHandle:Mn,useInsertionEffect:Mn,useLayoutEffect:Mn,useMemo:Mn,useReducer:Mn,useRef:Mn,useState:Mn,useDebugValue:Mn,useDeferredValue:Mn,useTransition:Mn,useMutableSource:Mn,useSyncExternalStore:Mn,useId:Mn,unstable_isNewReconciler:!1},JB={readContext:Yr,useCallback:function(e,t){return Di().memoizedState=[e,t===void 0?null:t],e},useContext:Yr,useEffect:C5,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,ig(4194308,4,a9.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ig(4194308,4,e,t)},useInsertionEffect:function(e,t){return ig(4,2,e,t)},useMemo:function(e,t){var n=Di();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Di();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=QB.bind(null,kt,e),[r.memoizedState,e]},useRef:function(e){var t=Di();return e={current:e},t.memoizedState=e},useState:x5,useDebugValue:Uw,useDeferredValue:function(e){return Di().memoizedState=e},useTransition:function(){var e=x5(!1),t=e[0];return e=YB.bind(null,e[1]),Di().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=kt,i=Di();if(St){if(n===void 0)throw Error(Z(407));n=n()}else{if(n=t(),gn===null)throw Error(Z(349));Wa&30||JA(r,t,n)}i.memoizedState=n;var o={value:n,getSnapshot:t};return i.queue=o,C5(t9.bind(null,r,o,e),[e]),r.flags|=2048,Jd(9,e9.bind(null,r,o,n,t),void 0,null),n},useId:function(){var e=Di(),t=gn.identifierPrefix;if(St){var n=Eo,r=To;n=(r&~(1<<32-mi(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Qd++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[Vi]=t,e[Kd]=r,C9(e,t,!1,!1),t.stateNode=e;e:{switch(s=DS(n,r),n){case"dialog":ct("cancel",e),ct("close",e),i=r;break;case"iframe":case"object":case"embed":ct("load",e),i=r;break;case"video":case"audio":for(i=0;iHu&&(t.flags|=128,r=!0,Fc(o,!1),t.lanes=4194304)}else{if(!r)if(e=Xg(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Fc(o,!0),o.tail===null&&o.tailMode==="hidden"&&!s.alternate&&!St)return Nn(t),null}else 2*Bt()-o.renderingStartTime>Hu&&n!==1073741824&&(t.flags|=128,r=!0,Fc(o,!1),t.lanes=4194304);o.isBackwards?(s.sibling=t.child,t.child=s):(n=o.last,n!==null?n.sibling=s:t.child=s,o.last=s)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=Bt(),t.sibling=null,n=Et.current,at(Et,r?n&1|2:n&1),t):(Nn(t),null);case 22:case 23:return Xw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Cr&1073741824&&(Nn(t),t.subtreeFlags&6&&(t.flags|=8192)):Nn(t),null;case 24:return null;case 25:return null}throw Error(Z(156,t.tag))}function aj(e,t){switch(kw(t),t.tag){case 1:return gr(t.type)&&zg(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Uu(),ht(pr),ht(Bn),Fw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return $w(t),null;case 13:if(ht(Et),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(Z(340));Vu()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ht(Et),null;case 4:return Uu(),null;case 10:return Mw(t.type._context),null;case 22:case 23:return Xw(),null;case 24:return null;default:return null}}var up=!1,Fn=!1,lj=typeof WeakSet=="function"?WeakSet:Set,ae=null;function uu(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Mt(e,t,r)}else n.current=null}function l_(e,t,n){try{n()}catch(r){Mt(e,t,r)}}var M5=!1;function uj(e,t){if(HS=Fg,e=OA(),Pw(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break e}var s=0,a=-1,l=-1,u=0,c=0,d=e,f=null;t:for(;;){for(var h;d!==n||i!==0&&d.nodeType!==3||(a=s+i),d!==o||r!==0&&d.nodeType!==3||(l=s+r),d.nodeType===3&&(s+=d.nodeValue.length),(h=d.firstChild)!==null;)f=d,d=h;for(;;){if(d===e)break t;if(f===n&&++u===i&&(a=s),f===o&&++c===r&&(l=s),(h=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=h}n=a===-1||l===-1?null:{start:a,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(qS={focusedElem:e,selectionRange:n},Fg=!1,ae=t;ae!==null;)if(t=ae,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,ae=e;else for(;ae!==null;){t=ae;try{var p=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(p!==null){var m=p.memoizedProps,S=p.memoizedState,v=t.stateNode,y=v.getSnapshotBeforeUpdate(t.elementType===t.type?m:ai(t.type,m),S);v.__reactInternalSnapshotBeforeUpdate=y}break;case 3:var g=t.stateNode.containerInfo;g.nodeType===1?g.textContent="":g.nodeType===9&&g.documentElement&&g.removeChild(g.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Z(163))}}catch(b){Mt(t,t.return,b)}if(e=t.sibling,e!==null){e.return=t.return,ae=e;break}ae=t.return}return p=M5,M5=!1,p}function xd(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var i=r=r.next;do{if((i.tag&e)===e){var o=i.destroy;i.destroy=void 0,o!==void 0&&l_(t,n,o)}i=i.next}while(i!==r)}}function ky(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function u_(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function P9(e){var t=e.alternate;t!==null&&(e.alternate=null,P9(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Vi],delete t[Kd],delete t[XS],delete t[HB],delete t[qB])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function A9(e){return e.tag===5||e.tag===3||e.tag===4}function N5(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||A9(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function c_(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Vg));else if(r!==4&&(e=e.child,e!==null))for(c_(e,t,n),e=e.sibling;e!==null;)c_(e,t,n),e=e.sibling}function d_(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(d_(e,t,n),e=e.sibling;e!==null;)d_(e,t,n),e=e.sibling}var Tn=null,li=!1;function ts(e,t,n){for(n=n.child;n!==null;)k9(e,t,n),n=n.sibling}function k9(e,t,n){if(Ki&&typeof Ki.onCommitFiberUnmount=="function")try{Ki.onCommitFiberUnmount(_y,n)}catch{}switch(n.tag){case 5:Fn||uu(n,t);case 6:var r=Tn,i=li;Tn=null,ts(e,t,n),Tn=r,li=i,Tn!==null&&(li?(e=Tn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Tn.removeChild(n.stateNode));break;case 18:Tn!==null&&(li?(e=Tn,n=n.stateNode,e.nodeType===8?X1(e.parentNode,n):e.nodeType===1&&X1(e,n),Ud(e)):X1(Tn,n.stateNode));break;case 4:r=Tn,i=li,Tn=n.stateNode.containerInfo,li=!0,ts(e,t,n),Tn=r,li=i;break;case 0:case 11:case 14:case 15:if(!Fn&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var o=i,s=o.destroy;o=o.tag,s!==void 0&&(o&2||o&4)&&l_(n,t,s),i=i.next}while(i!==r)}ts(e,t,n);break;case 1:if(!Fn&&(uu(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){Mt(n,t,a)}ts(e,t,n);break;case 21:ts(e,t,n);break;case 22:n.mode&1?(Fn=(r=Fn)||n.memoizedState!==null,ts(e,t,n),Fn=r):ts(e,t,n);break;default:ts(e,t,n)}}function D5(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new lj),t.forEach(function(r){var i=vj.bind(null,e,r);n.has(r)||(n.add(r),r.then(i,i))})}}function oi(e,t){var n=t.deletions;if(n!==null)for(var r=0;ri&&(i=s),r&=~o}if(r=i,r=Bt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*dj(r/1960))-r,10e?16:e,bs===null)var r=!1;else{if(e=bs,bs=null,em=0,$e&6)throw Error(Z(331));var i=$e;for($e|=4,ae=e.current;ae!==null;){var o=ae,s=o.child;if(ae.flags&16){var a=o.deletions;if(a!==null){for(var l=0;lBt()-Ww?La(e,0):qw|=n),mr(e,t)}function $9(e,t){t===0&&(e.mode&1?(t=ep,ep<<=1,!(ep&130023424)&&(ep=4194304)):t=1);var n=Zn();e=Fo(e,t),e!==null&&(eh(e,t,n),mr(e,n))}function yj(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),$9(e,n)}function vj(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(Z(314))}r!==null&&r.delete(t),$9(e,n)}var F9;F9=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||pr.current)dr=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return dr=!1,oj(e,t,n);dr=!!(e.flags&131072)}else dr=!1,St&&t.flags&1048576&&VA(t,Hg,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;og(e,t),e=t.pendingProps;var i=ju(t,Bn.current);_u(t,n),i=jw(null,t,r,e,i,n);var o=Vw();return t.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,gr(r)?(o=!0,Ug(t)):o=!1,t.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,Dw(t),i.updater=Py,t.stateNode=i,i._reactInternals=t,t_(t,r,e,n),t=i_(null,t,r,!0,o,n)):(t.tag=0,St&&o&&Aw(t),Yn(null,t,i,n),t=t.child),t;case 16:r=t.elementType;e:{switch(og(e,t),e=t.pendingProps,i=r._init,r=i(r._payload),t.type=r,i=t.tag=Sj(r),e=ai(r,e),i){case 0:t=r_(null,t,r,e,n);break e;case 1:t=O5(null,t,r,e,n);break e;case 11:t=A5(null,t,r,e,n);break e;case 14:t=k5(null,t,r,ai(r.type,e),n);break e}throw Error(Z(306,r,""))}return t;case 0:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:ai(r,i),r_(e,t,r,i,n);case 1:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:ai(r,i),O5(e,t,r,i,n);case 3:e:{if(_9(t),e===null)throw Error(Z(387));r=t.pendingProps,o=t.memoizedState,i=o.element,HA(e,t),Kg(t,r,null,n);var s=t.memoizedState;if(r=s.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){i=Gu(Error(Z(423)),t),t=R5(e,t,r,n,i);break e}else if(r!==i){i=Gu(Error(Z(424)),t),t=R5(e,t,r,n,i);break e}else for(Er=Ts(t.stateNode.containerInfo.firstChild),Pr=t,St=!0,ci=null,n=XA(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Vu(),r===i){t=Bo(e,t,n);break e}Yn(e,t,r,n)}t=t.child}return t;case 5:return YA(t),e===null&&ZS(t),r=t.type,i=t.pendingProps,o=e!==null?e.memoizedProps:null,s=i.children,WS(r,i)?s=null:o!==null&&WS(r,o)&&(t.flags|=32),S9(e,t),Yn(e,t,s,n),t.child;case 6:return e===null&&ZS(t),null;case 13:return w9(e,t,n);case 4:return Lw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=zu(t,null,r,n):Yn(e,t,r,n),t.child;case 11:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:ai(r,i),A5(e,t,r,i,n);case 7:return Yn(e,t,t.pendingProps,n),t.child;case 8:return Yn(e,t,t.pendingProps.children,n),t.child;case 12:return Yn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,i=t.pendingProps,o=t.memoizedProps,s=i.value,at(qg,r._currentValue),r._currentValue=s,o!==null)if(wi(o.value,s)){if(o.children===i.children&&!pr.current){t=Bo(e,t,n);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var a=o.dependencies;if(a!==null){s=o.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(o.tag===1){l=ko(-1,n&-n),l.tag=2;var u=o.updateQueue;if(u!==null){u=u.shared;var c=u.pending;c===null?l.next=l:(l.next=c.next,c.next=l),u.pending=l}}o.lanes|=n,l=o.alternate,l!==null&&(l.lanes|=n),JS(o.return,n,t),a.lanes|=n;break}l=l.next}}else if(o.tag===10)s=o.type===t.type?null:o.child;else if(o.tag===18){if(s=o.return,s===null)throw Error(Z(341));s.lanes|=n,a=s.alternate,a!==null&&(a.lanes|=n),JS(s,n,t),s=o.sibling}else s=o.child;if(s!==null)s.return=o;else for(s=o;s!==null;){if(s===t){s=null;break}if(o=s.sibling,o!==null){o.return=s.return,s=o;break}s=s.return}o=s}Yn(e,t,i.children,n),t=t.child}return t;case 9:return i=t.type,r=t.pendingProps.children,_u(t,n),i=Yr(i),r=r(i),t.flags|=1,Yn(e,t,r,n),t.child;case 14:return r=t.type,i=ai(r,t.pendingProps),i=ai(r.type,i),k5(e,t,r,i,n);case 15:return v9(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:ai(r,i),og(e,t),t.tag=1,gr(r)?(e=!0,Ug(t)):e=!1,_u(t,n),WA(t,r,i),t_(t,r,i,n),i_(null,t,r,!0,e,n);case 19:return x9(e,t,n);case 22:return b9(e,t,n)}throw Error(Z(156,t.tag))};function B9(e,t){return dA(e,t)}function bj(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Wr(e,t,n,r){return new bj(e,t,n,r)}function Qw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Sj(e){if(typeof e=="function")return Qw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===mw)return 11;if(e===yw)return 14}return 2}function ks(e,t){var n=e.alternate;return n===null?(n=Wr(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function lg(e,t,n,r,i,o){var s=2;if(r=e,typeof e=="function")Qw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case eu:return $a(n.children,i,o,t);case gw:s=8,i|=8;break;case TS:return e=Wr(12,n,t,i|2),e.elementType=TS,e.lanes=o,e;case ES:return e=Wr(13,n,t,i),e.elementType=ES,e.lanes=o,e;case PS:return e=Wr(19,n,t,i),e.elementType=PS,e.lanes=o,e;case K8:return Ry(n,i,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case q8:s=10;break e;case W8:s=9;break e;case mw:s=11;break e;case yw:s=14;break e;case ls:s=16,r=null;break e}throw Error(Z(130,e==null?e:typeof e,""))}return t=Wr(s,n,t,i),t.elementType=e,t.type=r,t.lanes=o,t}function $a(e,t,n,r){return e=Wr(7,e,r,t),e.lanes=n,e}function Ry(e,t,n,r){return e=Wr(22,e,r,t),e.elementType=K8,e.lanes=n,e.stateNode={isHidden:!1},e}function rb(e,t,n){return e=Wr(6,e,null,t),e.lanes=n,e}function ib(e,t,n){return t=Wr(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function _j(e,t,n,r,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=F1(0),this.expirationTimes=F1(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=F1(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function Zw(e,t,n,r,i,o,s,a,l){return e=new _j(e,t,n,a,l),t===1?(t=1,o===!0&&(t|=8)):t=0,o=Wr(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Dw(o),e}function wj(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(U9)}catch(e){console.error(e)}}U9(),V8.exports=Mr;var zi=V8.exports;const cwe=al(zi);var U5=zi;xS.createRoot=U5.createRoot,xS.hydrateRoot=U5.hydrateRoot;const Pj="modulepreload",Aj=function(e,t){return new URL(e,t).href},G5={},G9=function(t,n,r){if(!n||n.length===0)return t();const i=document.getElementsByTagName("link");return Promise.all(n.map(o=>{if(o=Aj(o,r),o in G5)return;G5[o]=!0;const s=o.endsWith(".css"),a=s?'[rel="stylesheet"]':"";if(!!r)for(let c=i.length-1;c>=0;c--){const d=i[c];if(d.href===o&&(!s||d.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${o}"]${a}`))return;const u=document.createElement("link");if(u.rel=s?"stylesheet":Pj,s||(u.as="script",u.crossOrigin=""),u.href=o,document.head.appendChild(u),s)return new Promise((c,d)=>{u.addEventListener("load",c),u.addEventListener("error",()=>d(new Error(`Unable to preload CSS for ${o}`)))})})).then(()=>t()).catch(o=>{const s=new Event("vite:preloadError",{cancelable:!0});if(s.payload=o,window.dispatchEvent(s),!s.defaultPrevented)throw o})};var H9={exports:{}},q9={};/** + * @license React + * use-sync-external-store-shim.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var qu=k;function kj(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Oj=typeof Object.is=="function"?Object.is:kj,Rj=qu.useState,Ij=qu.useEffect,Mj=qu.useLayoutEffect,Nj=qu.useDebugValue;function Dj(e,t){var n=t(),r=Rj({inst:{value:n,getSnapshot:t}}),i=r[0].inst,o=r[1];return Mj(function(){i.value=n,i.getSnapshot=t,ob(i)&&o({inst:i})},[e,n,t]),Ij(function(){return ob(i)&&o({inst:i}),e(function(){ob(i)&&o({inst:i})})},[e]),Nj(n),n}function ob(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Oj(e,n)}catch{return!0}}function Lj(e,t){return t()}var $j=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Lj:Dj;q9.useSyncExternalStore=qu.useSyncExternalStore!==void 0?qu.useSyncExternalStore:$j;H9.exports=q9;var Fj=H9.exports,W9={exports:{}},K9={};/** + * @license React + * use-sync-external-store-shim/with-selector.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Ly=k,Bj=Fj;function jj(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Vj=typeof Object.is=="function"?Object.is:jj,zj=Bj.useSyncExternalStore,Uj=Ly.useRef,Gj=Ly.useEffect,Hj=Ly.useMemo,qj=Ly.useDebugValue;K9.useSyncExternalStoreWithSelector=function(e,t,n,r,i){var o=Uj(null);if(o.current===null){var s={hasValue:!1,value:null};o.current=s}else s=o.current;o=Hj(function(){function l(h){if(!u){if(u=!0,c=h,h=r(h),i!==void 0&&s.hasValue){var p=s.value;if(i(p,h))return d=p}return d=h}if(p=d,Vj(c,h))return p;var m=r(h);return i!==void 0&&i(p,m)?p:(c=h,d=m)}var u=!1,c,d,f=n===void 0?null:n;return[function(){return l(t())},f===null?void 0:function(){return l(f())}]},[t,n,r,i]);var a=zj(e,o[0],o[1]);return Gj(function(){s.hasValue=!0,s.value=a},[a]),qj(a),a};W9.exports=K9;var X9=W9.exports;const Wj=al(X9);function Kj(e){e()}let Y9=Kj;const Xj=e=>Y9=e,Yj=()=>Y9,H5=Symbol.for(`react-redux-context-${k.version}`),q5=globalThis;function Qj(){let e=q5[H5];return e||(e=k.createContext(null),q5[H5]=e),e}const Fs=new Proxy({},new Proxy({},{get(e,t){const n=Qj();return(r,...i)=>Reflect[t](n,...i)}}));function nx(e=Fs){return function(){return k.useContext(e)}}const Q9=nx(),Zj=()=>{throw new Error("uSES not initialized!")};let Z9=Zj;const Jj=e=>{Z9=e},eV=(e,t)=>e===t;function tV(e=Fs){const t=e===Fs?Q9:nx(e);return function(r,i={}){const{equalityFn:o=eV,stabilityCheck:s=void 0,noopCheck:a=void 0}=typeof i=="function"?{equalityFn:i}:i,{store:l,subscription:u,getServerState:c,stabilityCheck:d,noopCheck:f}=t();k.useRef(!0);const h=k.useCallback({[r.name](m){return r(m)}}[r.name],[r,d,s]),p=Z9(u.addNestedSub,l.getState,c||l.getState,h,o);return k.useDebugValue(p),p}}const J9=tV();function rm(){return rm=Object.assign?Object.assign.bind():function(e){for(var t=1;t{let r=t;for(;r;)r.callback(),r=r.next})},get(){let r=[],i=t;for(;i;)r.push(i),i=i.next;return r},subscribe(r){let i=!0,o=n={callback:r,next:null,prev:n};return o.prev?o.prev.next=o:t=o,function(){!i||t===null||(i=!1,o.next?o.next.prev=o.prev:n=o.prev,o.prev?o.prev.next=o.next:t=o.next)}}}}const W5={notify(){},get:()=>[]};function hV(e,t){let n,r=W5;function i(d){return l(),r.subscribe(d)}function o(){r.notify()}function s(){c.onStateChange&&c.onStateChange()}function a(){return!!n}function l(){n||(n=t?t.addNestedSub(s):e.subscribe(s),r=fV())}function u(){n&&(n(),n=void 0,r.clear(),r=W5)}const c={addNestedSub:i,notifyNestedSubs:o,handleChangeWrapper:s,isSubscribed:a,trySubscribe:l,tryUnsubscribe:u,getListeners:()=>r};return c}const pV=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",gV=pV?k.useLayoutEffect:k.useEffect;function K5(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function im(e,t){if(K5(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let i=0;i{const u=hV(e);return{store:e,subscription:u,getServerState:r?()=>r:void 0,stabilityCheck:i,noopCheck:o}},[e,r,i,o]),a=k.useMemo(()=>e.getState(),[e]);gV(()=>{const{subscription:u}=s;return u.onStateChange=u.notifyNestedSubs,u.trySubscribe(),a!==e.getState()&&u.notifyNestedSubs(),()=>{u.tryUnsubscribe(),u.onStateChange=void 0}},[s,a]);const l=t||Fs;return We.createElement(l.Provider,{value:s},n)}function ok(e=Fs){const t=e===Fs?Q9:nx(e);return function(){const{store:r}=t();return r}}const sk=ok();function yV(e=Fs){const t=e===Fs?sk:ok(e);return function(){return t().dispatch}}const ak=yV();Jj(X9.useSyncExternalStoreWithSelector);Xj(zi.unstable_batchedUpdates);function pn(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r3?t.i-4:t.i:Array.isArray(e)?1:r0(e)?2:i0(e)?3:0}function Os(e,t){return Bs(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ug(e,t){return Bs(e)===2?e.get(t):e[t]}function lk(e,t,n){var r=Bs(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function uk(e,t){return e===t?e!==0||1/e==1/t:e!=e&&t!=t}function r0(e){return xV&&e instanceof Map}function i0(e){return CV&&e instanceof Set}function un(e){return e.o||e.t}function ux(e){if(Array.isArray(e))return Array.prototype.slice.call(e);var t=dk(e);delete t[_e];for(var n=Cu(t),r=0;r1&&(e.set=e.add=e.clear=e.delete=vV),Object.freeze(e),t&&jo(e,function(n,r){return ih(r,!0)},!0)),e}function vV(){pn(2)}function cx(e){return e==null||typeof e!="object"||Object.isFrozen(e)}function Yi(e){var t=y_[e];return t||pn(18,e),t}function dx(e,t){y_[e]||(y_[e]=t)}function tf(){return rf}function sb(e,t){t&&(Yi("Patches"),e.u=[],e.s=[],e.v=t)}function om(e){m_(e),e.p.forEach(bV),e.p=null}function m_(e){e===rf&&(rf=e.l)}function X5(e){return rf={p:[],l:rf,h:e,m:!0,_:0}}function bV(e){var t=e[_e];t.i===0||t.i===1?t.j():t.g=!0}function ab(e,t){t._=t.p.length;var n=t.p[0],r=e!==void 0&&e!==n;return t.h.O||Yi("ES5").S(t,e,r),r?(n[_e].P&&(om(t),pn(4)),yr(e)&&(e=sm(t,e),t.l||am(t,e)),t.u&&Yi("Patches").M(n[_e].t,e,t.u,t.s)):e=sm(t,n,[]),om(t),t.u&&t.v(t.u,t.s),e!==s0?e:void 0}function sm(e,t,n){if(cx(t))return t;var r=t[_e];if(!r)return jo(t,function(a,l){return Y5(e,r,t,a,l,n)},!0),t;if(r.A!==e)return t;if(!r.P)return am(e,r.t,!0),r.t;if(!r.I){r.I=!0,r.A._--;var i=r.i===4||r.i===5?r.o=ux(r.k):r.o,o=i,s=!1;r.i===3&&(o=new Set(i),i.clear(),s=!0),jo(o,function(a,l){return Y5(e,r,i,a,l,n,s)}),am(e,i,!1),n&&e.u&&Yi("Patches").N(r,n,e.u,e.s)}return r.o}function Y5(e,t,n,r,i,o,s){if(er(i)){var a=sm(e,i,o&&t&&t.i!==3&&!Os(t.R,r)?o.concat(r):void 0);if(lk(n,r,a),!er(a))return;e.m=!1}else s&&n.add(i);if(yr(i)&&!cx(i)){if(!e.h.D&&e._<1)return;sm(e,i),t&&t.A.l||am(e,i)}}function am(e,t,n){n===void 0&&(n=!1),!e.l&&e.h.D&&e.m&&ih(t,n)}function lb(e,t){var n=e[_e];return(n?un(n):e)[t]}function Q5(e,t){if(t in e)for(var n=Object.getPrototypeOf(e);n;){var r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=Object.getPrototypeOf(n)}}function cr(e){e.P||(e.P=!0,e.l&&cr(e.l))}function ub(e){e.o||(e.o=ux(e.t))}function nf(e,t,n){var r=r0(t)?Yi("MapSet").F(t,n):i0(t)?Yi("MapSet").T(t,n):e.O?function(i,o){var s=Array.isArray(i),a={i:s?1:0,A:o?o.A:tf(),P:!1,I:!1,R:{},l:o,t:i,k:null,o:null,j:null,C:!1},l=a,u=of;s&&(l=[a],u=dd);var c=Proxy.revocable(l,u),d=c.revoke,f=c.proxy;return a.k=f,a.j=d,f}(t,n):Yi("ES5").J(t,n);return(n?n.A:tf()).p.push(r),r}function o0(e){return er(e)||pn(22,e),function t(n){if(!yr(n))return n;var r,i=n[_e],o=Bs(n);if(i){if(!i.P&&(i.i<4||!Yi("ES5").K(i)))return i.t;i.I=!0,r=Z5(n,o),i.I=!1}else r=Z5(n,o);return jo(r,function(s,a){i&&ug(i.t,s)===a||lk(r,s,t(a))}),o===3?new Set(r):r}(e)}function Z5(e,t){switch(t){case 2:return new Map(e);case 3:return Array.from(e)}return ux(e)}function fx(){function e(o,s){var a=i[o];return a?a.enumerable=s:i[o]=a={configurable:!0,enumerable:s,get:function(){var l=this[_e];return of.get(l,o)},set:function(l){var u=this[_e];of.set(u,o,l)}},a}function t(o){for(var s=o.length-1;s>=0;s--){var a=o[s][_e];if(!a.P)switch(a.i){case 5:r(a)&&cr(a);break;case 4:n(a)&&cr(a)}}}function n(o){for(var s=o.t,a=o.k,l=Cu(a),u=l.length-1;u>=0;u--){var c=l[u];if(c!==_e){var d=s[c];if(d===void 0&&!Os(s,c))return!0;var f=a[c],h=f&&f[_e];if(h?h.t!==d:!uk(f,d))return!0}}var p=!!s[_e];return l.length!==Cu(s).length+(p?0:1)}function r(o){var s=o.k;if(s.length!==o.t.length)return!0;var a=Object.getOwnPropertyDescriptor(s,s.length-1);if(a&&!a.get)return!0;for(var l=0;l1?v-1:0),g=1;g1?c-1:0),f=1;f=0;i--){var o=r[i];if(o.path.length===0&&o.op==="replace"){n=o.value;break}}i>-1&&(r=r.slice(i+1));var s=Yi("Patches").$;return er(n)?s(n,r):this.produce(n,function(a){return s(a,r)})},e}(),Or=new fk,hk=Or.produce,gx=Or.produceWithPatches.bind(Or),EV=Or.setAutoFreeze.bind(Or),PV=Or.setUseProxies.bind(Or),v_=Or.applyPatches.bind(Or),AV=Or.createDraft.bind(Or),kV=Or.finishDraft.bind(Or);const Js=hk,dwe=Object.freeze(Object.defineProperty({__proto__:null,Immer:fk,applyPatches:v_,castDraft:_V,castImmutable:wV,createDraft:AV,current:o0,default:Js,enableAllPlugins:SV,enableES5:fx,enableMapSet:ck,enablePatches:hx,finishDraft:kV,freeze:ih,immerable:xu,isDraft:er,isDraftable:yr,nothing:s0,original:lx,produce:hk,produceWithPatches:gx,setAutoFreeze:EV,setUseProxies:PV},Symbol.toStringTag,{value:"Module"}));function sf(e){"@babel/helpers - typeof";return sf=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},sf(e)}function OV(e,t){if(sf(e)!=="object"||e===null)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||"default");if(sf(r)!=="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function RV(e){var t=OV(e,"string");return sf(t)==="symbol"?t:String(t)}function IV(e,t,n){return t=RV(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function t4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function n4(e){for(var t=1;t"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(En(1));return n(oh)(e,t)}if(typeof e!="function")throw new Error(En(2));var i=e,o=t,s=[],a=s,l=!1;function u(){a===s&&(a=s.slice())}function c(){if(l)throw new Error(En(3));return o}function d(m){if(typeof m!="function")throw new Error(En(4));if(l)throw new Error(En(5));var S=!0;return u(),a.push(m),function(){if(S){if(l)throw new Error(En(6));S=!1,u();var y=a.indexOf(m);a.splice(y,1),s=null}}}function f(m){if(!MV(m))throw new Error(En(7));if(typeof m.type>"u")throw new Error(En(8));if(l)throw new Error(En(9));try{l=!0,o=i(o,m)}finally{l=!1}for(var S=s=a,v=0;v"u")throw new Error(En(12));if(typeof n(void 0,{type:Wu.PROBE_UNKNOWN_ACTION()})>"u")throw new Error(En(13))})}function pc(e){for(var t=Object.keys(e),n={},r=0;r"u")throw u&&u.type,new Error(En(14));d[h]=S,c=c||S!==m}return c=c||o.length!==Object.keys(l).length,c?d:l}}function i4(e,t){return function(){return t(e.apply(this,arguments))}}function gk(e,t){if(typeof e=="function")return i4(e,t);if(typeof e!="object"||e===null)throw new Error(En(16));var n={};for(var r in e){var i=e[r];typeof i=="function"&&(n[r]=i4(i,t))}return n}function Ku(){for(var e=arguments.length,t=new Array(e),n=0;n-1){var u=n[l];return l>0&&(n.splice(l,1),n.unshift(u)),u.value}return lm}function i(a,l){r(a)===lm&&(n.unshift({key:a,value:l}),n.length>e&&n.pop())}function o(){return n}function s(){n=[]}return{get:r,put:i,getEntries:o,clear:s}}var mk=function(t,n){return t===n};function FV(e){return function(n,r){if(n===null||r===null||n.length!==r.length)return!1;for(var i=n.length,o=0;o1?t-1:0),r=1;r0&&o[o.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!o||u[1]>o[0]&&u[1]",value:e};if(typeof e!="object"||e===null||o!=null&&o.has(e))return!1;for(var a=r!=null?r(e):Object.entries(e),l=i.length>0,u=function(S,v){var y=t?t+"."+S:S;if(l){var g=i.some(function(b){return b instanceof RegExp?b.test(y):y===b});if(g)return"continue"}if(!n(v))return{value:{keyPath:y,value:v}};if(typeof v=="object"&&(s=Ck(v,y,n,r,i,o),s))return{value:s}},c=0,d=a;c-1}function ez(e){return""+e}function kk(e){var t={},n=[],r,i={addCase:function(o,s){var a=typeof o=="string"?o:o.type;if(a in t)throw new Error("addCase cannot be called with two reducers for the same action type");return t[a]=s,i},addMatcher:function(o,s){return n.push({matcher:o,reducer:s}),i},addDefaultCase:function(o){return r=o,i}};return e(i),[t,n,r]}function tz(e){return typeof e=="function"}function Ok(e,t,n,r){n===void 0&&(n=[]);var i=typeof t=="function"?kk(t):[t,n,r],o=i[0],s=i[1],a=i[2],l;if(tz(e))l=function(){return b_(e())};else{var u=b_(e);l=function(){return u}}function c(d,f){d===void 0&&(d=l());var h=js([o[f.type]],s.filter(function(p){var m=p.matcher;return m(f)}).map(function(p){var m=p.reducer;return m}));return h.filter(function(p){return!!p}).length===0&&(h=[a]),h.reduce(function(p,m){if(m)if(er(p)){var S=p,v=m(S,f);return v===void 0?p:v}else{if(yr(p))return Js(p,function(y){return m(y,f)});var v=m(p,f);if(v===void 0){if(p===null)return p;throw Error("A case reducer on a non-draftable value must not return undefined")}return v}return p},d)}return c.getInitialState=l,c}function nz(e,t){return e+"/"+t}function Pt(e){var t=e.name;if(!t)throw new Error("`name` is a required option for createSlice");typeof process<"u";var n=typeof e.initialState=="function"?e.initialState:b_(e.initialState),r=e.reducers||{},i=Object.keys(r),o={},s={},a={};i.forEach(function(c){var d=r[c],f=nz(t,c),h,p;"reducer"in d?(h=d.reducer,p=d.prepare):h=d,o[c]=h,s[f]=h,a[c]=p?ue(f,p):ue(f)});function l(){var c=typeof e.extraReducers=="function"?kk(e.extraReducers):[e.extraReducers],d=c[0],f=d===void 0?{}:d,h=c[1],p=h===void 0?[]:h,m=c[2],S=m===void 0?void 0:m,v=fr(fr({},f),s);return Ok(n,function(y){for(var g in v)y.addCase(g,v[g]);for(var b=0,_=p;b<_.length;b++){var w=_[b];y.addMatcher(w.matcher,w.reducer)}S&&y.addDefaultCase(S)})}var u;return{name:t,reducer:function(c,d){return u||(u=l()),u(c,d)},actions:a,caseReducers:o,getInitialState:function(){return u||(u=l()),u.getInitialState()}}}function rz(){return{ids:[],entities:{}}}function iz(){function e(t){return t===void 0&&(t={}),Object.assign(rz(),t)}return{getInitialState:e}}function oz(){function e(t){var n=function(u){return u.ids},r=function(u){return u.entities},i=yo(n,r,function(u,c){return u.map(function(d){return c[d]})}),o=function(u,c){return c},s=function(u,c){return u[c]},a=yo(n,function(u){return u.length});if(!t)return{selectIds:n,selectEntities:r,selectAll:i,selectTotal:a,selectById:yo(r,o,s)};var l=yo(t,r);return{selectIds:yo(t,n),selectEntities:l,selectAll:yo(t,i),selectTotal:yo(t,a),selectById:yo(l,o,s)}}return{getSelectors:e}}function sz(e){var t=Lt(function(n,r){return e(r)});return function(r){return t(r,void 0)}}function Lt(e){return function(n,r){function i(s){return Ak(s)}var o=function(s){i(r)?e(r.payload,s):e(r,s)};return er(n)?(o(n),n):Js(n,o)}}function Ed(e,t){var n=t(e);return n}function Fa(e){return Array.isArray(e)||(e=Object.values(e)),e}function Rk(e,t,n){e=Fa(e);for(var r=[],i=[],o=0,s=e;o0;if(y){var g=p.filter(function(b){return u(S,b,m)}).length>0;g&&(m.ids=Object.keys(m.entities))}}function f(p,m){return h([p],m)}function h(p,m){var S=Rk(p,e,m),v=S[0],y=S[1];d(y,m),n(v,m)}return{removeAll:sz(l),addOne:Lt(t),addMany:Lt(n),setOne:Lt(r),setMany:Lt(i),setAll:Lt(o),updateOne:Lt(c),updateMany:Lt(d),upsertOne:Lt(f),upsertMany:Lt(h),removeOne:Lt(s),removeMany:Lt(a)}}function az(e,t){var n=Ik(e),r=n.removeOne,i=n.removeMany,o=n.removeAll;function s(y,g){return a([y],g)}function a(y,g){y=Fa(y);var b=y.filter(function(_){return!(Ed(_,e)in g.entities)});b.length!==0&&S(b,g)}function l(y,g){return u([y],g)}function u(y,g){y=Fa(y),y.length!==0&&S(y,g)}function c(y,g){y=Fa(y),g.entities={},g.ids=[],a(y,g)}function d(y,g){return f([y],g)}function f(y,g){for(var b=!1,_=0,w=y;_-1;return n&&r}function lh(e){return typeof e[0]=="function"&&"pending"in e[0]&&"fulfilled"in e[0]&&"rejected"in e[0]}function u0(){for(var e=[],t=0;t0)for(var g=h.getState(),b=Array.from(n.values()),_=0,w=b;_Math.floor(e/t)*t,Ui=(e,t)=>Math.round(e/t)*t;var Tz=typeof global=="object"&&global&&global.Object===Object&&global;const Yk=Tz;var Ez=typeof self=="object"&&self&&self.Object===Object&&self,Pz=Yk||Ez||Function("return this")();const oo=Pz;var Az=oo.Symbol;const Zr=Az;var Qk=Object.prototype,kz=Qk.hasOwnProperty,Oz=Qk.toString,jc=Zr?Zr.toStringTag:void 0;function Rz(e){var t=kz.call(e,jc),n=e[jc];try{e[jc]=void 0;var r=!0}catch{}var i=Oz.call(e);return r&&(t?e[jc]=n:delete e[jc]),i}var Iz=Object.prototype,Mz=Iz.toString;function Nz(e){return Mz.call(e)}var Dz="[object Null]",Lz="[object Undefined]",f4=Zr?Zr.toStringTag:void 0;function ta(e){return e==null?e===void 0?Lz:Dz:f4&&f4 in Object(e)?Rz(e):Nz(e)}function Ci(e){return e!=null&&typeof e=="object"}var $z="[object Symbol]";function c0(e){return typeof e=="symbol"||Ci(e)&&ta(e)==$z}function Zk(e,t){for(var n=-1,r=e==null?0:e.length,i=Array(r);++n0){if(++t>=gU)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}function bU(e){return function(){return e}}var SU=function(){try{var e=fl(Object,"defineProperty");return e({},"",{}),e}catch{}}();const fm=SU;var _U=fm?function(e,t){return fm(e,"toString",{configurable:!0,enumerable:!1,value:bU(t),writable:!0})}:d0;const wU=_U;var xU=vU(wU);const nO=xU;function rO(e,t){for(var n=-1,r=e==null?0:e.length;++n-1}var kU=9007199254740991,OU=/^(?:0|[1-9]\d*)$/;function _x(e,t){var n=typeof e;return t=t??kU,!!t&&(n=="number"||n!="symbol"&&OU.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=MU}function mc(e){return e!=null&&xx(e.length)&&!Sx(e)}function aO(e,t,n){if(!vr(n))return!1;var r=typeof t;return(r=="number"?mc(n)&&_x(t,n.length):r=="string"&&t in n)?fh(n[t],e):!1}function lO(e){return sO(function(t,n){var r=-1,i=n.length,o=i>1?n[i-1]:void 0,s=i>2?n[2]:void 0;for(o=e.length>3&&typeof o=="function"?(i--,o):void 0,s&&aO(n[0],n[1],s)&&(o=i<3?void 0:o,i=1),t=Object(t);++r-1}function KG(e,t){var n=this.__data__,r=f0(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}function Ho(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t0&&n(a)?t>1?gO(a,t-1,n,r,i):Ox(i,a):r||(i[i.length]=a)}return i}function fH(e){var t=e==null?0:e.length;return t?gO(e,1):[]}function hH(e){return nO(oO(e,void 0,fH),e+"")}var pH=hO(Object.getPrototypeOf,Object);const Rx=pH;var gH="[object Object]",mH=Function.prototype,yH=Object.prototype,mO=mH.toString,vH=yH.hasOwnProperty,bH=mO.call(Object);function yO(e){if(!Ci(e)||ta(e)!=gH)return!1;var t=Rx(e);if(t===null)return!0;var n=vH.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&mO.call(n)==bH}function vO(e,t,n){var r=-1,i=e.length;t<0&&(t=-t>i?0:i+t),n=n>i?i:n,n<0&&(n+=i),i=t>n?0:n-t>>>0,t>>>=0;for(var o=Array(i);++r=r?e:vO(e,t,n)}var _H="\\ud800-\\udfff",wH="\\u0300-\\u036f",xH="\\ufe20-\\ufe2f",CH="\\u20d0-\\u20ff",TH=wH+xH+CH,EH="\\ufe0e\\ufe0f",PH="\\u200d",AH=RegExp("["+PH+_H+TH+EH+"]");function Ix(e){return AH.test(e)}function kH(e){return e.split("")}var bO="\\ud800-\\udfff",OH="\\u0300-\\u036f",RH="\\ufe20-\\ufe2f",IH="\\u20d0-\\u20ff",MH=OH+RH+IH,NH="\\ufe0e\\ufe0f",DH="["+bO+"]",x_="["+MH+"]",C_="\\ud83c[\\udffb-\\udfff]",LH="(?:"+x_+"|"+C_+")",SO="[^"+bO+"]",_O="(?:\\ud83c[\\udde6-\\uddff]){2}",wO="[\\ud800-\\udbff][\\udc00-\\udfff]",$H="\\u200d",xO=LH+"?",CO="["+NH+"]?",FH="(?:"+$H+"(?:"+[SO,_O,wO].join("|")+")"+CO+xO+")*",BH=CO+xO+FH,jH="(?:"+[SO+x_+"?",x_,_O,wO,DH].join("|")+")",VH=RegExp(C_+"(?="+C_+")|"+jH+BH,"g");function zH(e){return e.match(VH)||[]}function UH(e){return Ix(e)?zH(e):kH(e)}function GH(e){return function(t){t=p0(t);var n=Ix(t)?UH(t):void 0,r=n?n[0]:t.charAt(0),i=n?SH(n,1).join(""):t.slice(1);return r[e]()+i}}var HH=GH("toUpperCase");const qH=HH;function TO(e,t,n,r){var i=-1,o=e==null?0:e.length;for(r&&o&&(n=e[++i]);++i=t?e:t)),e}function Ss(e,t,n){return n===void 0&&(n=t,t=void 0),n!==void 0&&(n=hb(n),n=n===n?n:0),t!==void 0&&(t=hb(t),t=t===t?t:0),Lq(hb(e),t,n)}function $q(){this.__data__=new Ho,this.size=0}function Fq(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}function Bq(e){return this.__data__.get(e)}function jq(e){return this.__data__.has(e)}var Vq=200;function zq(e,t){var n=this.__data__;if(n instanceof Ho){var r=n.__data__;if(!cf||r.lengtha))return!1;var u=o.get(e),c=o.get(t);if(u&&c)return u==t&&c==e;var d=-1,f=!0,h=n&wK?new df:void 0;for(o.set(e,t),o.set(t,e);++d1),o}),gc(e,HO(e),n),r&&(n=Ad(n,EX|PX|AX,TX));for(var i=t.length;i--;)sR(n,t[i]);return n});const _0=kX;var OX=nR("length");const RX=OX;var aR="\\ud800-\\udfff",IX="\\u0300-\\u036f",MX="\\ufe20-\\ufe2f",NX="\\u20d0-\\u20ff",DX=IX+MX+NX,LX="\\ufe0e\\ufe0f",$X="["+aR+"]",O_="["+DX+"]",R_="\\ud83c[\\udffb-\\udfff]",FX="(?:"+O_+"|"+R_+")",lR="[^"+aR+"]",uR="(?:\\ud83c[\\udde6-\\uddff]){2}",cR="[\\ud800-\\udbff][\\udc00-\\udfff]",BX="\\u200d",dR=FX+"?",fR="["+LX+"]?",jX="(?:"+BX+"(?:"+[lR,uR,cR].join("|")+")"+fR+dR+")*",VX=fR+dR+jX,zX="(?:"+[lR+O_+"?",O_,uR,cR,$X].join("|")+")",H4=RegExp(R_+"(?="+R_+")|"+zX+VX,"g");function UX(e){for(var t=H4.lastIndex=0;H4.test(e);)++t;return t}function GX(e){return Ix(e)?UX(e):RX(e)}function HX(e,t,n,r,i){return i(e,function(o,s,a){n=r?(r=!1,o):t(n,o,s,a)}),n}function Lx(e,t,n){var r=mn(e)?TO:HX,i=arguments.length<3;return r(e,y0(t),n,i,v0)}var qX="[object Map]",WX="[object Set]";function hR(e){if(e==null)return 0;if(mc(e))return _X(e)?GX(e):e.length;var t=Qu(e);return t==qX||t==WX?e.size:pO(e).length}function KX(e,t){var n;return v0(e,function(r,i,o){return n=t(r,i,o),!n}),!!n}function Ea(e,t,n){var r=mn(e)?QO:KX;return n&&aO(e,t,n)&&(t=void 0),r(e,y0(t))}var XX=Dq(function(e,t,n){return e+(n?" ":"")+qH(t)});const YX=XX;var QX=1/0,ZX=Au&&1/Dx(new Au([,-0]))[1]==QX?function(e){return new Au(e)}:pU;const JX=ZX;var eY=200;function pR(e,t,n){var r=-1,i=AU,o=e.length,s=!0,a=[],l=a;if(n)s=!1,i=mX;else if(o>=eY){var u=t?null:JX(e);if(u)return Dx(u);s=!1,i=ZO,l=new df}else l=t?[]:a;e:for(;++r{CX(e,t.payload)}}}),{configChanged:iY}=mR.actions,oY=mR.reducer,pwe={"sd-1":"Stable Diffusion 1.x","sd-2":"Stable Diffusion 2.x",sdxl:"Stable Diffusion XL","sdxl-refiner":"Stable Diffusion XL Refiner"},sY={"sd-1":{maxClip:12,markers:[0,1,2,3,4,8,12]},"sd-2":{maxClip:24,markers:[0,1,2,3,5,10,15,20,24]},sdxl:{maxClip:24,markers:[0,1,2,3,5,10,15,20,24]},"sdxl-refiner":{maxClip:24,markers:[0,1,2,3,5,10,15,20,24]}},gwe=0,aY=4294967295;var Ve;(function(e){e.assertEqual=i=>i;function t(i){}e.assertIs=t;function n(i){throw new Error}e.assertNever=n,e.arrayToEnum=i=>{const o={};for(const s of i)o[s]=s;return o},e.getValidEnumValues=i=>{const o=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(const a of o)s[a]=i[a];return e.objectValues(s)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const o=[];for(const s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},e.find=(i,o)=>{for(const s of i)if(o(s))return s},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&isFinite(i)&&Math.floor(i)===i;function r(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(Ve||(Ve={}));var I_;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(I_||(I_={}));const re=Ve.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ms=e=>{switch(typeof e){case"undefined":return re.undefined;case"string":return re.string;case"number":return isNaN(e)?re.nan:re.number;case"boolean":return re.boolean;case"function":return re.function;case"bigint":return re.bigint;case"symbol":return re.symbol;case"object":return Array.isArray(e)?re.array:e===null?re.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?re.promise:typeof Map<"u"&&e instanceof Map?re.map:typeof Set<"u"&&e instanceof Set?re.set:typeof Date<"u"&&e instanceof Date?re.date:re.object;default:return re.unknown}},ee=Ve.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),lY=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class bi extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(o){return o.message},r={_errors:[]},i=o=>{for(const s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let a=r,l=0;for(;ln.message){const n={},r=[];for(const i of this.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}bi.create=e=>new bi(e);const ff=(e,t)=>{let n;switch(e.code){case ee.invalid_type:e.received===re.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case ee.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Ve.jsonStringifyReplacer)}`;break;case ee.unrecognized_keys:n=`Unrecognized key(s) in object: ${Ve.joinValues(e.keys,", ")}`;break;case ee.invalid_union:n="Invalid input";break;case ee.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Ve.joinValues(e.options)}`;break;case ee.invalid_enum_value:n=`Invalid enum value. Expected ${Ve.joinValues(e.options)}, received '${e.received}'`;break;case ee.invalid_arguments:n="Invalid function arguments";break;case ee.invalid_return_type:n="Invalid function return type";break;case ee.invalid_date:n="Invalid date";break;case ee.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Ve.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case ee.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case ee.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case ee.custom:n="Invalid input";break;case ee.invalid_intersection_types:n="Intersection results could not be merged";break;case ee.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case ee.not_finite:n="Number must be finite";break;default:n=t.defaultError,Ve.assertNever(e)}return{message:n}};let yR=ff;function uY(e){yR=e}function pm(){return yR}const gm=e=>{const{data:t,path:n,errorMaps:r,issueData:i}=e,o=[...n,...i.path||[]],s={...i,path:o};let a="";const l=r.filter(u=>!!u).slice().reverse();for(const u of l)a=u(s,{data:t,defaultError:a}).message;return{...i,path:o,message:i.message||a}},cY=[];function oe(e,t){const n=gm({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,pm(),ff].filter(r=>!!r)});e.common.issues.push(n)}class jn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const i of n){if(i.status==="aborted")return be;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const i of n)r.push({key:await i.key,value:await i.value});return jn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const i of n){const{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return be;o.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),(typeof s.value<"u"||i.alwaysSet)&&(r[o.value]=s.value)}return{status:t.value,value:r}}}const be=Object.freeze({status:"aborted"}),vR=e=>({status:"dirty",value:e}),tr=e=>({status:"valid",value:e}),M_=e=>e.status==="aborted",N_=e=>e.status==="dirty",mm=e=>e.status==="valid",ym=e=>typeof Promise<"u"&&e instanceof Promise;var ge;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(ge||(ge={}));class eo{constructor(t,n,r,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const q4=(e,t)=>{if(mm(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new bi(e.common.issues);return this._error=n,this._error}}};function we(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(s,a)=>s.code!=="invalid_type"?{message:a.defaultError}:typeof a.data>"u"?{message:r??a.defaultError}:{message:n??a.defaultError},description:i}}class Ce{constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(t){return ms(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ms(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new jn,ctx:{common:t.parent.common,data:t.data,parsedType:ms(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(ym(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const i={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ms(t)},o=this._parseSync({data:t,path:i.path,parent:i});return q4(i,o)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ms(t)},i=this._parse({data:t,path:r.path,parent:r}),o=await(ym(i)?i:Promise.resolve(i));return q4(r,o)}refine(t,n){const r=i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n;return this._refinement((i,o)=>{const s=t(i),a=()=>o.addIssue({code:ee.custom,...r(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,i)=>t(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(t){return new Ti({schema:this,typeName:ye.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Oo.create(this,this._def)}nullable(){return el.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Si.create(this,this._def)}promise(){return Ju.create(this,this._def)}or(t){return mf.create([this,t],this._def)}and(t){return yf.create(this,t,this._def)}transform(t){return new Ti({...we(this._def),schema:this,typeName:ye.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new wf({...we(this._def),innerType:this,defaultValue:n,typeName:ye.ZodDefault})}brand(){return new SR({typeName:ye.ZodBranded,type:this,...we(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new _m({...we(this._def),innerType:this,catchValue:n,typeName:ye.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return mh.create(this,t)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const dY=/^c[^\s-]{8,}$/i,fY=/^[a-z][a-z0-9]*$/,hY=/[0-9A-HJKMNP-TV-Z]{26}/,pY=/^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i,gY=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/,mY=/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,yY=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,vY=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,bY=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):e.precision===0?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function SY(e,t){return!!((t==="v4"||!t)&&yY.test(e)||(t==="v6"||!t)&&vY.test(e))}class pi extends Ce{constructor(){super(...arguments),this._regex=(t,n,r)=>this.refinement(i=>t.test(i),{validation:n,code:ee.invalid_string,...ge.errToObj(r)}),this.nonempty=t=>this.min(1,ge.errToObj(t)),this.trim=()=>new pi({...this._def,checks:[...this._def.checks,{kind:"trim"}]}),this.toLowerCase=()=>new pi({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]}),this.toUpperCase=()=>new pi({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==re.string){const o=this._getOrReturnCtx(t);return oe(o,{code:ee.invalid_type,expected:re.string,received:o.parsedType}),be}const r=new jn;let i;for(const o of this._def.checks)if(o.kind==="min")t.data.lengtho.value&&(i=this._getOrReturnCtx(t,i),oe(i,{code:ee.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){const s=t.data.length>o.value,a=t.data.length"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...ge.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...ge.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...ge.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...ge.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...ge.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...ge.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...ge.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...ge.errToObj(n)})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new pi({checks:[],typeName:ye.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...we(e)})};function _Y(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,o=parseInt(e.toFixed(i).replace(".","")),s=parseInt(t.toFixed(i).replace(".",""));return o%s/Math.pow(10,i)}class zs extends Ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==re.number){const o=this._getOrReturnCtx(t);return oe(o,{code:ee.invalid_type,expected:re.number,received:o.parsedType}),be}let r;const i=new jn;for(const o of this._def.checks)o.kind==="int"?Ve.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),oe(r,{code:ee.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),oe(r,{code:ee.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?_Y(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),oe(r,{code:ee.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),oe(r,{code:ee.not_finite,message:o.message}),i.dirty()):Ve.assertNever(o);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,ge.toString(n))}gt(t,n){return this.setLimit("min",t,!1,ge.toString(n))}lte(t,n){return this.setLimit("max",t,!0,ge.toString(n))}lt(t,n){return this.setLimit("max",t,!1,ge.toString(n))}setLimit(t,n,r,i){return new zs({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:ge.toString(i)}]})}_addCheck(t){return new zs({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:ge.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ge.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ge.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ge.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ge.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:ge.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:ge.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ge.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ge.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&Ve.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.valuenew zs({checks:[],typeName:ye.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...we(e)});class Us extends Ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==re.bigint){const o=this._getOrReturnCtx(t);return oe(o,{code:ee.invalid_type,expected:re.bigint,received:o.parsedType}),be}let r;const i=new jn;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?t.datao.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),oe(r,{code:ee.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),oe(r,{code:ee.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Ve.assertNever(o);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,ge.toString(n))}gt(t,n){return this.setLimit("min",t,!1,ge.toString(n))}lte(t,n){return this.setLimit("max",t,!0,ge.toString(n))}lt(t,n){return this.setLimit("max",t,!1,ge.toString(n))}setLimit(t,n,r,i){return new Us({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:ge.toString(i)}]})}_addCheck(t){return new Us({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ge.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ge.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ge.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ge.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:ge.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new Us({checks:[],typeName:ye.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...we(e)})};class hf extends Ce{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==re.boolean){const r=this._getOrReturnCtx(t);return oe(r,{code:ee.invalid_type,expected:re.boolean,received:r.parsedType}),be}return tr(t.data)}}hf.create=e=>new hf({typeName:ye.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...we(e)});class Za extends Ce{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==re.date){const o=this._getOrReturnCtx(t);return oe(o,{code:ee.invalid_type,expected:re.date,received:o.parsedType}),be}if(isNaN(t.data.getTime())){const o=this._getOrReturnCtx(t);return oe(o,{code:ee.invalid_date}),be}const r=new jn;let i;for(const o of this._def.checks)o.kind==="min"?t.data.getTime()o.value&&(i=this._getOrReturnCtx(t,i),oe(i,{code:ee.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):Ve.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Za({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:ge.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:ge.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew Za({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ye.ZodDate,...we(e)});class vm extends Ce{_parse(t){if(this._getType(t)!==re.symbol){const r=this._getOrReturnCtx(t);return oe(r,{code:ee.invalid_type,expected:re.symbol,received:r.parsedType}),be}return tr(t.data)}}vm.create=e=>new vm({typeName:ye.ZodSymbol,...we(e)});class pf extends Ce{_parse(t){if(this._getType(t)!==re.undefined){const r=this._getOrReturnCtx(t);return oe(r,{code:ee.invalid_type,expected:re.undefined,received:r.parsedType}),be}return tr(t.data)}}pf.create=e=>new pf({typeName:ye.ZodUndefined,...we(e)});class gf extends Ce{_parse(t){if(this._getType(t)!==re.null){const r=this._getOrReturnCtx(t);return oe(r,{code:ee.invalid_type,expected:re.null,received:r.parsedType}),be}return tr(t.data)}}gf.create=e=>new gf({typeName:ye.ZodNull,...we(e)});class Zu extends Ce{constructor(){super(...arguments),this._any=!0}_parse(t){return tr(t.data)}}Zu.create=e=>new Zu({typeName:ye.ZodAny,...we(e)});class Ba extends Ce{constructor(){super(...arguments),this._unknown=!0}_parse(t){return tr(t.data)}}Ba.create=e=>new Ba({typeName:ye.ZodUnknown,...we(e)});class Vo extends Ce{_parse(t){const n=this._getOrReturnCtx(t);return oe(n,{code:ee.invalid_type,expected:re.never,received:n.parsedType}),be}}Vo.create=e=>new Vo({typeName:ye.ZodNever,...we(e)});class bm extends Ce{_parse(t){if(this._getType(t)!==re.undefined){const r=this._getOrReturnCtx(t);return oe(r,{code:ee.invalid_type,expected:re.void,received:r.parsedType}),be}return tr(t.data)}}bm.create=e=>new bm({typeName:ye.ZodVoid,...we(e)});class Si extends Ce{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==re.array)return oe(n,{code:ee.invalid_type,expected:re.array,received:n.parsedType}),be;if(i.exactLength!==null){const s=n.data.length>i.exactLength.value,a=n.data.lengthi.maxLength.value&&(oe(n,{code:ee.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>i.type._parseAsync(new eo(n,s,n.path,a)))).then(s=>jn.mergeArray(r,s));const o=[...n.data].map((s,a)=>i.type._parseSync(new eo(n,s,n.path,a)));return jn.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new Si({...this._def,minLength:{value:t,message:ge.toString(n)}})}max(t,n){return new Si({...this._def,maxLength:{value:t,message:ge.toString(n)}})}length(t,n){return new Si({...this._def,exactLength:{value:t,message:ge.toString(n)}})}nonempty(t){return this.min(1,t)}}Si.create=(e,t)=>new Si({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ye.ZodArray,...we(t)});function Wl(e){if(e instanceof Tt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Oo.create(Wl(r))}return new Tt({...e._def,shape:()=>t})}else return e instanceof Si?new Si({...e._def,type:Wl(e.element)}):e instanceof Oo?Oo.create(Wl(e.unwrap())):e instanceof el?el.create(Wl(e.unwrap())):e instanceof to?to.create(e.items.map(t=>Wl(t))):e}class Tt extends Ce{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=Ve.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==re.object){const u=this._getOrReturnCtx(t);return oe(u,{code:ee.invalid_type,expected:re.object,received:u.parsedType}),be}const{status:r,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Vo&&this._def.unknownKeys==="strip"))for(const u in i.data)s.includes(u)||a.push(u);const l=[];for(const u of s){const c=o[u],d=i.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new eo(i,d,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Vo){const u=this._def.unknownKeys;if(u==="passthrough")for(const c of a)l.push({key:{status:"valid",value:c},value:{status:"valid",value:i.data[c]}});else if(u==="strict")a.length>0&&(oe(i,{code:ee.unrecognized_keys,keys:a}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const c of a){const d=i.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new eo(i,d,i.path,c)),alwaysSet:c in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const u=[];for(const c of l){const d=await c.key;u.push({key:d,value:await c.value,alwaysSet:c.alwaysSet})}return u}).then(u=>jn.mergeObjectSync(r,u)):jn.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return ge.errToObj,new Tt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var i,o,s,a;const l=(s=(o=(i=this._def).errorMap)===null||o===void 0?void 0:o.call(i,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(a=ge.errToObj(t).message)!==null&&a!==void 0?a:l}:{message:l}}}:{}})}strip(){return new Tt({...this._def,unknownKeys:"strip"})}passthrough(){return new Tt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Tt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Tt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ye.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Tt({...this._def,catchall:t})}pick(t){const n={};return Ve.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Tt({...this._def,shape:()=>n})}omit(t){const n={};return Ve.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Tt({...this._def,shape:()=>n})}deepPartial(){return Wl(this)}partial(t){const n={};return Ve.objectKeys(this.shape).forEach(r=>{const i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}),new Tt({...this._def,shape:()=>n})}required(t){const n={};return Ve.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Oo;)o=o._def.innerType;n[r]=o}}),new Tt({...this._def,shape:()=>n})}keyof(){return bR(Ve.objectKeys(this.shape))}}Tt.create=(e,t)=>new Tt({shape:()=>e,unknownKeys:"strip",catchall:Vo.create(),typeName:ye.ZodObject,...we(t)});Tt.strictCreate=(e,t)=>new Tt({shape:()=>e,unknownKeys:"strict",catchall:Vo.create(),typeName:ye.ZodObject,...we(t)});Tt.lazycreate=(e,t)=>new Tt({shape:e,unknownKeys:"strip",catchall:Vo.create(),typeName:ye.ZodObject,...we(t)});class mf extends Ce{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function i(o){for(const a of o)if(a.result.status==="valid")return a.result;for(const a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;const s=o.map(a=>new bi(a.ctx.common.issues));return oe(n,{code:ee.invalid_union,unionErrors:s}),be}if(n.common.async)return Promise.all(r.map(async o=>{const s={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(i);{let o;const s=[];for(const l of r){const u={...n,common:{...n.common,issues:[]},parent:null},c=l._parseSync({data:n.data,path:n.path,parent:u});if(c.status==="valid")return c;c.status==="dirty"&&!o&&(o={result:c,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;const a=s.map(l=>new bi(l));return oe(n,{code:ee.invalid_union,unionErrors:a}),be}}get options(){return this._def.options}}mf.create=(e,t)=>new mf({options:e,typeName:ye.ZodUnion,...we(t)});const dg=e=>e instanceof bf?dg(e.schema):e instanceof Ti?dg(e.innerType()):e instanceof Sf?[e.value]:e instanceof Gs?e.options:e instanceof _f?Object.keys(e.enum):e instanceof wf?dg(e._def.innerType):e instanceof pf?[void 0]:e instanceof gf?[null]:null;class w0 extends Ce{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==re.object)return oe(n,{code:ee.invalid_type,expected:re.object,received:n.parsedType}),be;const r=this.discriminator,i=n.data[r],o=this.optionsMap.get(i);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(oe(n,{code:ee.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),be)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const i=new Map;for(const o of n){const s=dg(o.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const a of s){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,o)}}return new w0({typeName:ye.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...we(r)})}}function D_(e,t){const n=ms(e),r=ms(t);if(e===t)return{valid:!0,data:e};if(n===re.object&&r===re.object){const i=Ve.objectKeys(t),o=Ve.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(const a of o){const l=D_(e[a],t[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(n===re.array&&r===re.array){if(e.length!==t.length)return{valid:!1};const i=[];for(let o=0;o{if(M_(o)||M_(s))return be;const a=D_(o.value,s.value);return a.valid?((N_(o)||N_(s))&&n.dirty(),{status:n.value,value:a.data}):(oe(r,{code:ee.invalid_intersection_types}),be)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}yf.create=(e,t,n)=>new yf({left:e,right:t,typeName:ye.ZodIntersection,...we(n)});class to extends Ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==re.array)return oe(r,{code:ee.invalid_type,expected:re.array,received:r.parsedType}),be;if(r.data.lengththis._def.items.length&&(oe(r,{code:ee.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const o=[...r.data].map((s,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new eo(r,s,r.path,a)):null}).filter(s=>!!s);return r.common.async?Promise.all(o).then(s=>jn.mergeArray(n,s)):jn.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new to({...this._def,rest:t})}}to.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new to({items:e,typeName:ye.ZodTuple,rest:null,...we(t)})};class vf extends Ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==re.object)return oe(r,{code:ee.invalid_type,expected:re.object,received:r.parsedType}),be;const i=[],o=this._def.keyType,s=this._def.valueType;for(const a in r.data)i.push({key:o._parse(new eo(r,a,r.path,a)),value:s._parse(new eo(r,r.data[a],r.path,a))});return r.common.async?jn.mergeObjectAsync(n,i):jn.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Ce?new vf({keyType:t,valueType:n,typeName:ye.ZodRecord,...we(r)}):new vf({keyType:pi.create(),valueType:t,typeName:ye.ZodRecord,...we(n)})}}class Sm extends Ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==re.map)return oe(r,{code:ee.invalid_type,expected:re.map,received:r.parsedType}),be;const i=this._def.keyType,o=this._def.valueType,s=[...r.data.entries()].map(([a,l],u)=>({key:i._parse(new eo(r,a,r.path,[u,"key"])),value:o._parse(new eo(r,l,r.path,[u,"value"]))}));if(r.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of s){const u=await l.key,c=await l.value;if(u.status==="aborted"||c.status==="aborted")return be;(u.status==="dirty"||c.status==="dirty")&&n.dirty(),a.set(u.value,c.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const l of s){const u=l.key,c=l.value;if(u.status==="aborted"||c.status==="aborted")return be;(u.status==="dirty"||c.status==="dirty")&&n.dirty(),a.set(u.value,c.value)}return{status:n.value,value:a}}}}Sm.create=(e,t,n)=>new Sm({valueType:t,keyType:e,typeName:ye.ZodMap,...we(n)});class Ja extends Ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==re.set)return oe(r,{code:ee.invalid_type,expected:re.set,received:r.parsedType}),be;const i=this._def;i.minSize!==null&&r.data.sizei.maxSize.value&&(oe(r,{code:ee.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());const o=this._def.valueType;function s(l){const u=new Set;for(const c of l){if(c.status==="aborted")return be;c.status==="dirty"&&n.dirty(),u.add(c.value)}return{status:n.value,value:u}}const a=[...r.data.values()].map((l,u)=>o._parse(new eo(r,l,r.path,u)));return r.common.async?Promise.all(a).then(l=>s(l)):s(a)}min(t,n){return new Ja({...this._def,minSize:{value:t,message:ge.toString(n)}})}max(t,n){return new Ja({...this._def,maxSize:{value:t,message:ge.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}Ja.create=(e,t)=>new Ja({valueType:e,minSize:null,maxSize:null,typeName:ye.ZodSet,...we(t)});class ku extends Ce{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==re.function)return oe(n,{code:ee.invalid_type,expected:re.function,received:n.parsedType}),be;function r(a,l){return gm({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,pm(),ff].filter(u=>!!u),issueData:{code:ee.invalid_arguments,argumentsError:l}})}function i(a,l){return gm({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,pm(),ff].filter(u=>!!u),issueData:{code:ee.invalid_return_type,returnTypeError:l}})}const o={errorMap:n.common.contextualErrorMap},s=n.data;return this._def.returns instanceof Ju?tr(async(...a)=>{const l=new bi([]),u=await this._def.args.parseAsync(a,o).catch(f=>{throw l.addIssue(r(a,f)),l}),c=await s(...u);return await this._def.returns._def.type.parseAsync(c,o).catch(f=>{throw l.addIssue(i(c,f)),l})}):tr((...a)=>{const l=this._def.args.safeParse(a,o);if(!l.success)throw new bi([r(a,l.error)]);const u=s(...l.data),c=this._def.returns.safeParse(u,o);if(!c.success)throw new bi([i(u,c.error)]);return c.data})}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new ku({...this._def,args:to.create(t).rest(Ba.create())})}returns(t){return new ku({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new ku({args:t||to.create([]).rest(Ba.create()),returns:n||Ba.create(),typeName:ye.ZodFunction,...we(r)})}}class bf extends Ce{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}bf.create=(e,t)=>new bf({getter:e,typeName:ye.ZodLazy,...we(t)});class Sf extends Ce{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return oe(n,{received:n.data,code:ee.invalid_literal,expected:this._def.value}),be}return{status:"valid",value:t.data}}get value(){return this._def.value}}Sf.create=(e,t)=>new Sf({value:e,typeName:ye.ZodLiteral,...we(t)});function bR(e,t){return new Gs({values:e,typeName:ye.ZodEnum,...we(t)})}class Gs extends Ce{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return oe(n,{expected:Ve.joinValues(r),received:n.parsedType,code:ee.invalid_type}),be}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return oe(n,{received:n.data,code:ee.invalid_enum_value,options:r}),be}return tr(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t){return Gs.create(t)}exclude(t){return Gs.create(this.options.filter(n=>!t.includes(n)))}}Gs.create=bR;class _f extends Ce{_parse(t){const n=Ve.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==re.string&&r.parsedType!==re.number){const i=Ve.objectValues(n);return oe(r,{expected:Ve.joinValues(i),received:r.parsedType,code:ee.invalid_type}),be}if(n.indexOf(t.data)===-1){const i=Ve.objectValues(n);return oe(r,{received:r.data,code:ee.invalid_enum_value,options:i}),be}return tr(t.data)}get enum(){return this._def.values}}_f.create=(e,t)=>new _f({values:e,typeName:ye.ZodNativeEnum,...we(t)});class Ju extends Ce{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==re.promise&&n.common.async===!1)return oe(n,{code:ee.invalid_type,expected:re.promise,received:n.parsedType}),be;const r=n.parsedType===re.promise?n.data:Promise.resolve(n.data);return tr(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Ju.create=(e,t)=>new Ju({type:e,typeName:ye.ZodPromise,...we(t)});class Ti extends Ce{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ye.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null;if(i.type==="preprocess"){const s=i.transform(r.data);return r.common.async?Promise.resolve(s).then(a=>this._def.schema._parseAsync({data:a,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}const o={addIssue:s=>{oe(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="refinement"){const s=a=>{const l=i.refinement(a,o);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?be:(a.status==="dirty"&&n.dirty(),s(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?be:(a.status==="dirty"&&n.dirty(),s(a.value).then(()=>({status:n.value,value:a.value}))))}if(i.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!mm(s))return s;const a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>mm(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:n.value,value:a})):s);Ve.assertNever(i)}}Ti.create=(e,t,n)=>new Ti({schema:e,typeName:ye.ZodEffects,effect:t,...we(n)});Ti.createWithPreprocess=(e,t,n)=>new Ti({schema:t,effect:{type:"preprocess",transform:e},typeName:ye.ZodEffects,...we(n)});class Oo extends Ce{_parse(t){return this._getType(t)===re.undefined?tr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Oo.create=(e,t)=>new Oo({innerType:e,typeName:ye.ZodOptional,...we(t)});class el extends Ce{_parse(t){return this._getType(t)===re.null?tr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}el.create=(e,t)=>new el({innerType:e,typeName:ye.ZodNullable,...we(t)});class wf extends Ce{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===re.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}wf.create=(e,t)=>new wf({innerType:e,typeName:ye.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...we(t)});class _m extends Ce{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ym(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new bi(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new bi(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}_m.create=(e,t)=>new _m({innerType:e,typeName:ye.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...we(t)});class wm extends Ce{_parse(t){if(this._getType(t)!==re.nan){const r=this._getOrReturnCtx(t);return oe(r,{code:ee.invalid_type,expected:re.nan,received:r.parsedType}),be}return{status:"valid",value:t.data}}}wm.create=e=>new wm({typeName:ye.ZodNaN,...we(e)});const wY=Symbol("zod_brand");class SR extends Ce{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class mh extends Ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?be:o.status==="dirty"?(n.dirty(),vR(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{const i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?be:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(t,n){return new mh({in:t,out:n,typeName:ye.ZodPipeline})}}const _R=(e,t={},n)=>e?Zu.create().superRefine((r,i)=>{var o,s;if(!e(r)){const a=typeof t=="function"?t(r):typeof t=="string"?{message:t}:t,l=(s=(o=a.fatal)!==null&&o!==void 0?o:n)!==null&&s!==void 0?s:!0,u=typeof a=="string"?{message:a}:a;i.addIssue({code:"custom",...u,fatal:l})}}):Zu.create(),xY={object:Tt.lazycreate};var ye;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline"})(ye||(ye={}));const CY=(e,t={message:`Input not instance of ${e.name}`})=>_R(n=>n instanceof e,t),wR=pi.create,xR=zs.create,TY=wm.create,EY=Us.create,CR=hf.create,PY=Za.create,AY=vm.create,kY=pf.create,OY=gf.create,RY=Zu.create,IY=Ba.create,MY=Vo.create,NY=bm.create,DY=Si.create,LY=Tt.create,$Y=Tt.strictCreate,FY=mf.create,BY=w0.create,jY=yf.create,VY=to.create,zY=vf.create,UY=Sm.create,GY=Ja.create,HY=ku.create,qY=bf.create,WY=Sf.create,KY=Gs.create,XY=_f.create,YY=Ju.create,W4=Ti.create,QY=Oo.create,ZY=el.create,JY=Ti.createWithPreprocess,eQ=mh.create,tQ=()=>wR().optional(),nQ=()=>xR().optional(),rQ=()=>CR().optional(),iQ={string:e=>pi.create({...e,coerce:!0}),number:e=>zs.create({...e,coerce:!0}),boolean:e=>hf.create({...e,coerce:!0}),bigint:e=>Us.create({...e,coerce:!0}),date:e=>Za.create({...e,coerce:!0})},oQ=be;var jt=Object.freeze({__proto__:null,defaultErrorMap:ff,setErrorMap:uY,getErrorMap:pm,makeIssue:gm,EMPTY_PATH:cY,addIssueToContext:oe,ParseStatus:jn,INVALID:be,DIRTY:vR,OK:tr,isAborted:M_,isDirty:N_,isValid:mm,isAsync:ym,get util(){return Ve},get objectUtil(){return I_},ZodParsedType:re,getParsedType:ms,ZodType:Ce,ZodString:pi,ZodNumber:zs,ZodBigInt:Us,ZodBoolean:hf,ZodDate:Za,ZodSymbol:vm,ZodUndefined:pf,ZodNull:gf,ZodAny:Zu,ZodUnknown:Ba,ZodNever:Vo,ZodVoid:bm,ZodArray:Si,ZodObject:Tt,ZodUnion:mf,ZodDiscriminatedUnion:w0,ZodIntersection:yf,ZodTuple:to,ZodRecord:vf,ZodMap:Sm,ZodSet:Ja,ZodFunction:ku,ZodLazy:bf,ZodLiteral:Sf,ZodEnum:Gs,ZodNativeEnum:_f,ZodPromise:Ju,ZodEffects:Ti,ZodTransformer:Ti,ZodOptional:Oo,ZodNullable:el,ZodDefault:wf,ZodCatch:_m,ZodNaN:wm,BRAND:wY,ZodBranded:SR,ZodPipeline:mh,custom:_R,Schema:Ce,ZodSchema:Ce,late:xY,get ZodFirstPartyTypeKind(){return ye},coerce:iQ,any:RY,array:DY,bigint:EY,boolean:CR,date:PY,discriminatedUnion:BY,effect:W4,enum:KY,function:HY,instanceof:CY,intersection:jY,lazy:qY,literal:WY,map:UY,nan:TY,nativeEnum:XY,never:MY,null:OY,nullable:ZY,number:xR,object:LY,oboolean:rQ,onumber:nQ,optional:QY,ostring:tQ,pipeline:eQ,preprocess:JY,promise:YY,record:zY,set:GY,strictObject:$Y,string:wR,symbol:AY,transformer:W4,tuple:VY,undefined:kY,union:FY,unknown:IY,void:NY,NEVER:oQ,ZodIssueCode:ee,quotelessJson:lY,ZodError:bi});const sQ=jt.string(),mwe=e=>sQ.safeParse(e).success,aQ=jt.string(),ywe=e=>aQ.safeParse(e).success;jt.string();jt.string();const lQ=jt.number().int().min(1),vwe=e=>lQ.safeParse(e).success,uQ=jt.number().min(1),bwe=e=>uQ.safeParse(e).success,cQ=jt.enum(["euler","deis","ddim","ddpm","dpmpp_2s","dpmpp_2m","dpmpp_2m_sde","dpmpp_sde","heun","kdpm_2","lms","pndm","unipc","euler_k","dpmpp_2s_k","dpmpp_2m_k","dpmpp_2m_sde_k","dpmpp_sde_k","heun_k","lms_k","euler_a","kdpm_2_a"]),Swe=e=>cQ.safeParse(e).success,_we={euler:"Euler",deis:"DEIS",ddim:"DDIM",ddpm:"DDPM",dpmpp_sde:"DPM++ SDE",dpmpp_2s:"DPM++ 2S",dpmpp_2m:"DPM++ 2M",dpmpp_2m_sde:"DPM++ 2M SDE",heun:"Heun",kdpm_2:"KDPM 2",lms:"LMS",pndm:"PNDM",unipc:"UniPC",euler_k:"Euler Karras",dpmpp_sde_k:"DPM++ SDE Karras",dpmpp_2s_k:"DPM++ 2S Karras",dpmpp_2m_k:"DPM++ 2M Karras",dpmpp_2m_sde_k:"DPM++ 2M SDE Karras",heun_k:"Heun Karras",lms_k:"LMS Karras",euler_a:"Euler Ancestral",kdpm_2_a:"KDPM 2 Ancestral"},dQ=jt.number().int().min(0).max(aY),wwe=e=>dQ.safeParse(e).success,fQ=jt.number().multipleOf(8).min(64),xwe=e=>fQ.safeParse(e).success,hQ=jt.number().multipleOf(8).min(64),Cwe=e=>hQ.safeParse(e).success,x0=jt.enum(["sd-1","sd-2","sdxl","sdxl-refiner"]),xf=jt.object({model_name:jt.string().min(1),base_model:x0}),Twe=e=>xf.safeParse(e).success,pQ=jt.object({model_name:jt.string().min(1),base_model:x0}),Ewe=jt.object({model_name:jt.string().min(1),base_model:x0}),Pwe=jt.object({model_name:jt.string().min(1),base_model:x0}),gQ=jt.number().min(0).max(1),Awe=e=>gQ.safeParse(e).success;jt.enum(["fp16","fp32"]);const Wo={cfgScale:7.5,height:512,img2imgStrength:.75,infillMethod:"patchmatch",iterations:1,perlin:0,positivePrompt:"",negativePrompt:"",scheduler:"euler",seamBlur:16,seamSize:96,seamSteps:30,seamStrength:.7,seed:0,seedWeights:"",shouldFitToWidthHeight:!0,shouldGenerateVariations:!1,shouldRandomizeSeed:!0,shouldUseNoiseSettings:!1,steps:50,threshold:0,tileSize:32,variationAmount:.1,width:512,shouldUseSymmetry:!1,horizontalSymmetrySteps:0,verticalSymmetrySteps:0,model:null,vae:null,vaePrecision:"fp32",seamlessXAxis:!1,seamlessYAxis:!1,clipSkip:0,shouldUseCpuNoise:!0,shouldShowAdvancedOptions:!1,aspectRatio:null},mQ=Wo,TR=Pt({name:"generation",initialState:mQ,reducers:{setPositivePrompt:(e,t)=>{e.positivePrompt=t.payload},setNegativePrompt:(e,t)=>{e.negativePrompt=t.payload},setIterations:(e,t)=>{e.iterations=t.payload},setSteps:(e,t)=>{e.steps=t.payload},clampSymmetrySteps:e=>{e.horizontalSymmetrySteps=Ss(e.horizontalSymmetrySteps,0,e.steps),e.verticalSymmetrySteps=Ss(e.verticalSymmetrySteps,0,e.steps)},setCfgScale:(e,t)=>{e.cfgScale=t.payload},setThreshold:(e,t)=>{e.threshold=t.payload},setPerlin:(e,t)=>{e.perlin=t.payload},setHeight:(e,t)=>{e.height=t.payload},setWidth:(e,t)=>{e.width=t.payload},toggleSize:e=>{const[t,n]=[e.width,e.height];e.width=n,e.height=t},setScheduler:(e,t)=>{e.scheduler=t.payload},setSeed:(e,t)=>{e.seed=t.payload,e.shouldRandomizeSeed=!1},setImg2imgStrength:(e,t)=>{e.img2imgStrength=t.payload},setSeamlessXAxis:(e,t)=>{e.seamlessXAxis=t.payload},setSeamlessYAxis:(e,t)=>{e.seamlessYAxis=t.payload},setShouldFitToWidthHeight:(e,t)=>{e.shouldFitToWidthHeight=t.payload},resetSeed:e=>{e.seed=-1},setShouldGenerateVariations:(e,t)=>{e.shouldGenerateVariations=t.payload},setVariationAmount:(e,t)=>{e.variationAmount=t.payload},setSeedWeights:(e,t)=>{e.seedWeights=t.payload,e.shouldGenerateVariations=!0,e.variationAmount=0},resetParametersState:e=>({...e,...Wo}),setShouldRandomizeSeed:(e,t)=>{e.shouldRandomizeSeed=t.payload},clearInitialImage:e=>{e.initialImage=void 0},setSeamSize:(e,t)=>{e.seamSize=t.payload},setSeamBlur:(e,t)=>{e.seamBlur=t.payload},setSeamStrength:(e,t)=>{e.seamStrength=t.payload},setSeamSteps:(e,t)=>{e.seamSteps=t.payload},setTileSize:(e,t)=>{e.tileSize=t.payload},setInfillMethod:(e,t)=>{e.infillMethod=t.payload},setShouldUseSymmetry:(e,t)=>{e.shouldUseSymmetry=t.payload},setHorizontalSymmetrySteps:(e,t)=>{e.horizontalSymmetrySteps=t.payload},setVerticalSymmetrySteps:(e,t)=>{e.verticalSymmetrySteps=t.payload},setShouldUseNoiseSettings:(e,t)=>{e.shouldUseNoiseSettings=t.payload},initialImageChanged:(e,t)=>{const{image_name:n,width:r,height:i}=t.payload;e.initialImage={imageName:n,width:r,height:i}},modelChanged:(e,t)=>{if(e.model=t.payload,e.model===null)return;const{maxClip:n}=sY[e.model.base_model];e.clipSkip=Ss(e.clipSkip,0,n)},vaeSelected:(e,t)=>{e.vae=t.payload},vaePrecisionChanged:(e,t)=>{e.vaePrecision=t.payload},setClipSkip:(e,t)=>{e.clipSkip=t.payload},shouldUseCpuNoiseChanged:(e,t)=>{e.shouldUseCpuNoise=t.payload},setShouldShowAdvancedOptions:(e,t)=>{e.shouldShowAdvancedOptions=t.payload,t.payload||(e.clipSkip=0)},setAspectRatio:(e,t)=>{const n=t.payload;e.aspectRatio=n,n&&(e.height=Ui(e.width/n,8))}},extraReducers:e=>{e.addCase(iY,(t,n)=>{var i;const r=(i=n.payload.sd)==null?void 0:i.defaultModel;if(r&&!t.model){const[o,s,a]=r.split("/"),l=xf.safeParse({model_name:a,base_model:o});l.success&&(t.model=l.data)}}),e.addCase(vQ,(t,n)=>{n.payload||(t.clipSkip=0)})}}),{clampSymmetrySteps:kwe,clearInitialImage:ER,resetParametersState:Owe,resetSeed:Rwe,setCfgScale:Iwe,setWidth:Mwe,setHeight:Nwe,toggleSize:Dwe,setImg2imgStrength:Lwe,setInfillMethod:yQ,setIterations:$we,setPerlin:Fwe,setPositivePrompt:Bwe,setNegativePrompt:jwe,setScheduler:Vwe,setSeamBlur:zwe,setSeamSize:Uwe,setSeamSteps:Gwe,setSeamStrength:Hwe,setSeed:qwe,setSeedWeights:Wwe,setShouldFitToWidthHeight:Kwe,setShouldGenerateVariations:Xwe,setShouldRandomizeSeed:Ywe,setSteps:Qwe,setThreshold:Zwe,setTileSize:Jwe,setVariationAmount:exe,setShouldUseSymmetry:txe,setHorizontalSymmetrySteps:nxe,setVerticalSymmetrySteps:rxe,initialImageChanged:C0,modelChanged:ja,vaeSelected:PR,setShouldUseNoiseSettings:ixe,setSeamlessXAxis:oxe,setSeamlessYAxis:sxe,setClipSkip:axe,shouldUseCpuNoiseChanged:lxe,setShouldShowAdvancedOptions:vQ,setAspectRatio:bQ,vaePrecisionChanged:uxe}=TR.actions,SQ=TR.reducer,AR=["txt2img","img2img","unifiedCanvas","nodes","modelManager","batch"],K4=(e,t)=>{typeof t=="number"?e.activeTab=t:e.activeTab=AR.indexOf(t)},kR={activeTab:0,shouldPinParametersPanel:!0,shouldShowParametersPanel:!0,shouldShowImageDetails:!1,shouldUseCanvasBetaLayout:!1,shouldShowExistingModelsInSearch:!1,shouldUseSliders:!1,shouldPinGallery:!0,shouldShowGallery:!0,shouldHidePreview:!1,shouldShowProgressInViewer:!0,shouldShowEmbeddingPicker:!1,favoriteSchedulers:[]},OR=Pt({name:"ui",initialState:kR,reducers:{setActiveTab:(e,t)=>{K4(e,t.payload)},setShouldPinParametersPanel:(e,t)=>{e.shouldPinParametersPanel=t.payload,e.shouldShowParametersPanel=!0},setShouldShowParametersPanel:(e,t)=>{e.shouldShowParametersPanel=t.payload},setShouldShowImageDetails:(e,t)=>{e.shouldShowImageDetails=t.payload},setShouldUseCanvasBetaLayout:(e,t)=>{e.shouldUseCanvasBetaLayout=t.payload},setShouldHidePreview:(e,t)=>{e.shouldHidePreview=t.payload},setShouldShowExistingModelsInSearch:(e,t)=>{e.shouldShowExistingModelsInSearch=t.payload},setShouldUseSliders:(e,t)=>{e.shouldUseSliders=t.payload},setShouldShowGallery:(e,t)=>{e.shouldShowGallery=t.payload},togglePinGalleryPanel:e=>{e.shouldPinGallery=!e.shouldPinGallery,e.shouldPinGallery||(e.shouldShowGallery=!0)},togglePinParametersPanel:e=>{e.shouldPinParametersPanel=!e.shouldPinParametersPanel,e.shouldPinParametersPanel||(e.shouldShowParametersPanel=!0)},toggleParametersPanel:e=>{e.shouldShowParametersPanel=!e.shouldShowParametersPanel},toggleGalleryPanel:e=>{e.shouldShowGallery=!e.shouldShowGallery},togglePanels:e=>{e.shouldShowGallery||e.shouldShowParametersPanel?(e.shouldShowGallery=!1,e.shouldShowParametersPanel=!1):(e.shouldShowGallery=!0,e.shouldShowParametersPanel=!0)},setShouldShowProgressInViewer:(e,t)=>{e.shouldShowProgressInViewer=t.payload},favoriteSchedulersChanged:(e,t)=>{e.favoriteSchedulers=t.payload},toggleEmbeddingPicker:e=>{e.shouldShowEmbeddingPicker=!e.shouldShowEmbeddingPicker}},extraReducers(e){e.addCase(C0,t=>{K4(t,"img2img")})}}),{setActiveTab:RR,setShouldPinParametersPanel:cxe,setShouldShowParametersPanel:dxe,setShouldShowImageDetails:fxe,setShouldUseCanvasBetaLayout:_Q,setShouldShowExistingModelsInSearch:hxe,setShouldUseSliders:pxe,setShouldHidePreview:gxe,setShouldShowGallery:mxe,togglePanels:yxe,togglePinGalleryPanel:vxe,togglePinParametersPanel:bxe,toggleParametersPanel:Sxe,toggleGalleryPanel:_xe,setShouldShowProgressInViewer:wxe,favoriteSchedulersChanged:xxe,toggleEmbeddingPicker:Cxe}=OR.actions,wQ=OR.reducer;let Wn=[],T0=(e,t)=>{let n=[],r={get(){return r.lc||r.listen(()=>{})(),r.value},l:t||0,lc:0,listen(i,o){return r.lc=n.push(i,o||r.l)/2,()=>{let s=n.indexOf(i);~s&&(n.splice(s,2),r.lc--,r.lc||r.off())}},notify(i){let o=!Wn.length;for(let s=0;s(e.events=e.events||{},e.events[n+mp]||(e.events[n+mp]=r(i=>{e.events[n].reduceRight((o,s)=>(s(o),o),{shared:{},...i})})),e.events[n]=e.events[n]||[],e.events[n].push(t),()=>{let i=e.events[n],o=i.indexOf(t);i.splice(o,1),i.length||(delete e.events[n],e.events[n+mp](),delete e.events[n+mp])}),TQ=1e3,EQ=(e,t)=>CQ(e,r=>{let i=t(r);i&&e.events[gp].push(i)},xQ,r=>{let i=e.listen;e.listen=(...s)=>(!e.lc&&!e.active&&(e.active=!0,r()),i(...s));let o=e.off;return e.events[gp]=[],e.off=()=>{o(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let s of e.events[gp])s();e.events[gp]=[]}},TQ)},()=>{e.listen=i,e.off=o}}),PQ=(e,t)=>{Array.isArray(e)||(e=[e]);let n,r=()=>{let o=e.map(s=>s.get());(n===void 0||o.some((s,a)=>s!==n[a]))&&(n=o,i.set(t(...o)))},i=T0(void 0,Math.max(...e.map(o=>o.l))+1);return EQ(i,()=>{let o=e.map(s=>s.listen(r,i.l));return r(),()=>{for(let s of o)s()}}),i};const AQ={"Content-Type":"application/json"},kQ=/\/*$/;function OQ(e){const t=new URLSearchParams;if(e&&typeof e=="object")for(const[n,r]of Object.entries(e))r!=null&&t.set(n,r);return t.toString()}function RQ(e){return JSON.stringify(e)}function IQ(e,t){let n=`${t.baseUrl?t.baseUrl.replace(kQ,""):""}${e}`;if(t.params.path)for(const[r,i]of Object.entries(t.params.path))n=n.replace(`{${r}}`,encodeURIComponent(String(i)));if(t.params.query){const r=t.querySerializer(t.params.query);r&&(n+=`?${r}`)}return n}function MQ(e={}){const{fetch:t=globalThis.fetch,querySerializer:n,bodySerializer:r,...i}=e,o=new Headers({...AQ,...i.headers??{}});async function s(a,l){const{headers:u,body:c,params:d={},parseAs:f="json",querySerializer:h=n??OQ,bodySerializer:p=r??RQ,...m}=l||{},S=IQ(a,{baseUrl:i.baseUrl,params:d,querySerializer:h}),v=new Headers(o),y=new Headers(u);for(const[w,x]of y.entries())x==null?v.delete(w):v.set(w,x);const g={redirect:"follow",...i,...m,headers:v};c&&(g.body=p(c)),g.body instanceof FormData&&v.delete("Content-Type");const b=await t(S,g);if(b.status===204||b.headers.get("Content-Length")==="0")return b.ok?{data:{},response:b}:{error:{},response:b};if(b.ok){let w=b.body;if(f!=="stream"){const x=b.clone();w=typeof x[f]=="function"?await x[f]():await x.text()}return{data:w,response:b}}let _={};try{_=await b.clone().json()}catch{_=await b.clone().text()}return{error:_,response:b}}return{async get(a,l){return s(a,{...l,method:"GET"})},async put(a,l){return s(a,{...l,method:"PUT"})},async post(a,l){return s(a,{...l,method:"POST"})},async del(a,l){return s(a,{...l,method:"DELETE"})},async options(a,l){return s(a,{...l,method:"OPTIONS"})},async head(a,l){return s(a,{...l,method:"HEAD"})},async patch(a,l){return s(a,{...l,method:"PATCH"})},async trace(a,l){return s(a,{...l,method:"TRACE"})}}}const Cf=T0(),Tf=T0(),E0=PQ([Cf,Tf],(e,t)=>MQ({headers:e?{Authorization:`Bearer ${e}`}:{},baseUrl:`${t??""}`})),On=Vs("api/sessionCreated",async(e,{rejectWithValue:t})=>{const{graph:n}=e,{post:r}=E0.get(),{data:i,error:o,response:s}=await r("/api/v1/sessions/",{body:n});return o?t({arg:e,status:s.status,error:o}):i}),NQ=e=>vr(e)&&"status"in e,yh=Vs("api/sessionInvoked",async(e,{rejectWithValue:t})=>{const{session_id:n}=e,{put:r}=E0.get(),{data:i,error:o,response:s}=await r("/api/v1/sessions/{session_id}/invoke",{params:{query:{all:!0},path:{session_id:n}}});if(o)return NQ(o)&&o.status===403?t({arg:e,status:s.status,error:o.body.detail}):t({arg:e,status:s.status,error:o})}),hl=Vs("api/sessionCanceled",async(e,{rejectWithValue:t})=>{const{session_id:n}=e,{del:r}=E0.get(),{data:i,error:o,response:s}=await r("/api/v1/sessions/{session_id}/invoke",{params:{path:{session_id:n}}});return o?t({arg:e,error:o}):i});Vs("api/listSessions",async(e,{rejectWithValue:t})=>{const{params:n}=e,{get:r}=E0.get(),{data:i,error:o,response:s}=await r("/api/v1/sessions/",{params:n});return o?t({arg:e,error:o}):i});const IR=ei(On.rejected,yh.rejected),Ml=(e,t,n,r,i,o,s)=>{const a=Math.floor(e/2-(n+i/2)*s),l=Math.floor(t/2-(r+o/2)*s);return{x:a,y:l}},Nl=(e,t,n,r,i=.95)=>{const o=e*i/n,s=t*i/r;return Math.min(1,Math.min(o,s))},Txe=.999,Exe=.1,Pxe=20,Vc=.95,Axe=30,kxe=10,X4=e=>({x:Math.floor(e.x),y:Math.floor(e.y)}),pa=e=>{const{width:t,height:n}=e,r={width:t,height:n},i=512*512,o=t/n;let s=t*n,a=448;for(;s1?(r.width=a,r.height=Ui(a/o,64)):o<1&&(r.height=a,r.width=Ui(a*o,64)),s=r.width*r.height;return r},DQ=e=>({width:Ui(e.width,64),height:Ui(e.height,64)}),Oxe=[{label:"Base",value:"base"},{label:"Mask",value:"mask"}],Rxe=[{label:"Auto",value:"auto"},{label:"Manual",value:"manual"},{label:"None",value:"none"}],MR=e=>e.kind==="line"&&e.layer==="mask",Ixe=e=>e.kind==="line"&&e.layer==="base",Y4=e=>e.kind==="image"&&e.layer==="base",Mxe=e=>e.kind==="fillRect"&&e.layer==="base",Nxe=e=>e.kind==="eraseRect"&&e.layer==="base",LQ=e=>e.kind==="line",Kl={objects:[],stagingArea:{images:[],selectedImageIndex:-1}},NR={boundingBoxCoordinates:{x:0,y:0},boundingBoxDimensions:{width:512,height:512},boundingBoxPreviewFill:{r:0,g:0,b:0,a:.5},boundingBoxScaleMethod:"auto",brushColor:{r:90,g:90,b:255,a:1},brushSize:50,canvasContainerDimensions:{width:0,height:0},colorPickerColor:{r:90,g:90,b:255,a:1},cursorPosition:null,doesCanvasNeedScaling:!1,futureLayerStates:[],isCanvasInitialized:!1,isDrawing:!1,isMaskEnabled:!0,isMouseOverBoundingBox:!1,isMoveBoundingBoxKeyHeld:!1,isMoveStageKeyHeld:!1,isMovingBoundingBox:!1,isMovingStage:!1,isTransformingBoundingBox:!1,layer:"base",layerState:Kl,maskColor:{r:255,g:90,b:90,a:1},maxHistory:128,minimumStageScale:1,pastLayerStates:[],scaledBoundingBoxDimensions:{width:512,height:512},shouldAntialias:!0,shouldAutoSave:!1,shouldCropToBoundingBoxOnSave:!1,shouldDarkenOutsideBoundingBox:!1,shouldLockBoundingBox:!1,shouldPreserveMaskedArea:!1,shouldRestrictStrokesToBox:!0,shouldShowBoundingBox:!0,shouldShowBrush:!0,shouldShowBrushPreview:!1,shouldShowCanvasDebugInfo:!1,shouldShowCheckboardTransparency:!1,shouldShowGrid:!0,shouldShowIntermediates:!0,shouldShowStagingImage:!0,shouldShowStagingOutline:!0,shouldSnapToGrid:!0,stageCoordinates:{x:0,y:0},stageDimensions:{width:0,height:0},stageScale:1,tool:"brush"},DR=Pt({name:"canvas",initialState:NR,reducers:{setTool:(e,t)=>{const n=t.payload;e.tool=t.payload,n!=="move"&&(e.isTransformingBoundingBox=!1,e.isMouseOverBoundingBox=!1,e.isMovingBoundingBox=!1,e.isMovingStage=!1)},setLayer:(e,t)=>{e.layer=t.payload},toggleTool:e=>{const t=e.tool;t!=="move"&&(e.tool=t==="brush"?"eraser":"brush")},setMaskColor:(e,t)=>{e.maskColor=t.payload},setBrushColor:(e,t)=>{e.brushColor=t.payload},setBrushSize:(e,t)=>{e.brushSize=t.payload},clearMask:e=>{e.pastLayerStates.push(Ln(e.layerState)),e.layerState.objects=e.layerState.objects.filter(t=>!MR(t)),e.futureLayerStates=[],e.shouldPreserveMaskedArea=!1},toggleShouldInvertMask:e=>{e.shouldPreserveMaskedArea=!e.shouldPreserveMaskedArea},toggleShouldShowMask:e=>{e.isMaskEnabled=!e.isMaskEnabled},setShouldPreserveMaskedArea:(e,t)=>{e.shouldPreserveMaskedArea=t.payload},setIsMaskEnabled:(e,t)=>{e.isMaskEnabled=t.payload,e.layer=t.payload?"mask":"base"},setShouldShowCheckboardTransparency:(e,t)=>{e.shouldShowCheckboardTransparency=t.payload},setShouldShowBrushPreview:(e,t)=>{e.shouldShowBrushPreview=t.payload},setShouldShowBrush:(e,t)=>{e.shouldShowBrush=t.payload},setCursorPosition:(e,t)=>{e.cursorPosition=t.payload},setInitialCanvasImage:(e,t)=>{const n=t.payload,{width:r,height:i}=n,{stageDimensions:o}=e,s={width:hp(Ss(r,64,512),64),height:hp(Ss(i,64,512),64)},a={x:Ui(r/2-s.width/2,64),y:Ui(i/2-s.height/2,64)};if(e.boundingBoxScaleMethod==="auto"){const c=pa(s);e.scaledBoundingBoxDimensions=c}e.boundingBoxDimensions=s,e.boundingBoxCoordinates=a,e.pastLayerStates.push(Ln(e.layerState)),e.layerState={...Kl,objects:[{kind:"image",layer:"base",x:0,y:0,width:r,height:i,imageName:n.image_name}]},e.futureLayerStates=[],e.isCanvasInitialized=!1;const l=Nl(o.width,o.height,r,i,Vc),u=Ml(o.width,o.height,0,0,r,i,l);e.stageScale=l,e.stageCoordinates=u,e.doesCanvasNeedScaling=!0},setBoundingBoxDimensions:(e,t)=>{const n=DQ(t.payload);if(e.boundingBoxDimensions=n,e.boundingBoxScaleMethod==="auto"){const r=pa(n);e.scaledBoundingBoxDimensions=r}},flipBoundingBoxAxes:e=>{const[t,n]=[e.boundingBoxDimensions.width,e.boundingBoxDimensions.height];e.boundingBoxDimensions={width:n,height:t}},setBoundingBoxCoordinates:(e,t)=>{e.boundingBoxCoordinates=X4(t.payload)},setStageCoordinates:(e,t)=>{e.stageCoordinates=t.payload},setBoundingBoxPreviewFill:(e,t)=>{e.boundingBoxPreviewFill=t.payload},setDoesCanvasNeedScaling:(e,t)=>{e.doesCanvasNeedScaling=t.payload},setStageScale:(e,t)=>{e.stageScale=t.payload},setShouldDarkenOutsideBoundingBox:(e,t)=>{e.shouldDarkenOutsideBoundingBox=t.payload},setIsDrawing:(e,t)=>{e.isDrawing=t.payload},clearCanvasHistory:e=>{e.pastLayerStates=[],e.futureLayerStates=[]},setShouldLockBoundingBox:(e,t)=>{e.shouldLockBoundingBox=t.payload},toggleShouldLockBoundingBox:e=>{e.shouldLockBoundingBox=!e.shouldLockBoundingBox},setShouldShowBoundingBox:(e,t)=>{e.shouldShowBoundingBox=t.payload},setIsTransformingBoundingBox:(e,t)=>{e.isTransformingBoundingBox=t.payload},setIsMovingBoundingBox:(e,t)=>{e.isMovingBoundingBox=t.payload},setIsMouseOverBoundingBox:(e,t)=>{e.isMouseOverBoundingBox=t.payload},setIsMoveBoundingBoxKeyHeld:(e,t)=>{e.isMoveBoundingBoxKeyHeld=t.payload},setIsMoveStageKeyHeld:(e,t)=>{e.isMoveStageKeyHeld=t.payload},canvasSessionIdChanged:(e,t)=>{e.layerState.stagingArea.sessionId=t.payload},stagingAreaInitialized:(e,t)=>{const{sessionId:n,boundingBox:r}=t.payload;e.layerState.stagingArea={boundingBox:r,sessionId:n,images:[],selectedImageIndex:-1}},addImageToStagingArea:(e,t)=>{const n=t.payload;!n||!e.layerState.stagingArea.boundingBox||(e.pastLayerStates.push(Ln(e.layerState)),e.pastLayerStates.length>e.maxHistory&&e.pastLayerStates.shift(),e.layerState.stagingArea.images.push({kind:"image",layer:"base",...e.layerState.stagingArea.boundingBox,imageName:n.image_name}),e.layerState.stagingArea.selectedImageIndex=e.layerState.stagingArea.images.length-1,e.futureLayerStates=[])},discardStagedImages:e=>{e.pastLayerStates.push(Ln(e.layerState)),e.pastLayerStates.length>e.maxHistory&&e.pastLayerStates.shift(),e.layerState.stagingArea={...Kl.stagingArea},e.futureLayerStates=[],e.shouldShowStagingOutline=!0,e.shouldShowStagingOutline=!0},addFillRect:e=>{const{boundingBoxCoordinates:t,boundingBoxDimensions:n,brushColor:r}=e;e.pastLayerStates.push(Ln(e.layerState)),e.pastLayerStates.length>e.maxHistory&&e.pastLayerStates.shift(),e.layerState.objects.push({kind:"fillRect",layer:"base",...t,...n,color:r}),e.futureLayerStates=[]},addEraseRect:e=>{const{boundingBoxCoordinates:t,boundingBoxDimensions:n}=e;e.pastLayerStates.push(Ln(e.layerState)),e.pastLayerStates.length>e.maxHistory&&e.pastLayerStates.shift(),e.layerState.objects.push({kind:"eraseRect",layer:"base",...t,...n}),e.futureLayerStates=[]},addLine:(e,t)=>{const{tool:n,layer:r,brushColor:i,brushSize:o,shouldRestrictStrokesToBox:s}=e;if(n==="move"||n==="colorPicker")return;const a=o/2,l=r==="base"&&n==="brush"?{color:i}:{};e.pastLayerStates.push(Ln(e.layerState)),e.pastLayerStates.length>e.maxHistory&&e.pastLayerStates.shift();const u={kind:"line",layer:r,tool:n,strokeWidth:a,points:t.payload,...l};s&&(u.clip={...e.boundingBoxCoordinates,...e.boundingBoxDimensions}),e.layerState.objects.push(u),e.futureLayerStates=[]},addPointToCurrentLine:(e,t)=>{const n=e.layerState.objects.findLast(LQ);n&&n.points.push(...t.payload)},undo:e=>{const t=e.pastLayerStates.pop();t&&(e.futureLayerStates.unshift(Ln(e.layerState)),e.futureLayerStates.length>e.maxHistory&&e.futureLayerStates.pop(),e.layerState=t)},redo:e=>{const t=e.futureLayerStates.shift();t&&(e.pastLayerStates.push(Ln(e.layerState)),e.pastLayerStates.length>e.maxHistory&&e.pastLayerStates.shift(),e.layerState=t)},setShouldShowGrid:(e,t)=>{e.shouldShowGrid=t.payload},setIsMovingStage:(e,t)=>{e.isMovingStage=t.payload},setShouldSnapToGrid:(e,t)=>{e.shouldSnapToGrid=t.payload},setShouldAutoSave:(e,t)=>{e.shouldAutoSave=t.payload},setShouldShowIntermediates:(e,t)=>{e.shouldShowIntermediates=t.payload},resetCanvas:e=>{e.pastLayerStates.push(Ln(e.layerState)),e.layerState=Kl,e.futureLayerStates=[]},setCanvasContainerDimensions:(e,t)=>{e.canvasContainerDimensions=t.payload},resizeAndScaleCanvas:e=>{const{width:t,height:n}=e.canvasContainerDimensions,r=e.layerState.objects.find(Y4),i={width:Math.floor(t),height:Math.floor(n)};if(!r){const c=Nl(i.width,i.height,512,512,Vc),d=Ml(i.width,i.height,0,0,512,512,c),f={width:512,height:512};if(e.stageScale=c,e.stageCoordinates=d,e.stageDimensions=i,e.boundingBoxCoordinates={x:0,y:0},e.boundingBoxDimensions=f,e.boundingBoxScaleMethod==="auto"){const h=pa(f);e.scaledBoundingBoxDimensions=h}return}const{width:o,height:s}=r,l=Nl(t,n,o,s,.95),u=Ml(i.width,i.height,0,0,o,s,l);e.minimumStageScale=l,e.stageScale=l,e.stageCoordinates=X4(u),e.stageDimensions=i,e.isCanvasInitialized=!0},resizeCanvas:e=>{const{width:t,height:n}=e.canvasContainerDimensions,r={width:Math.floor(t),height:Math.floor(n)};if(e.stageDimensions=r,!e.layerState.objects.find(Y4)){const i=Nl(r.width,r.height,512,512,Vc),o=Ml(r.width,r.height,0,0,512,512,i),s={width:512,height:512};if(e.stageScale=i,e.stageCoordinates=o,e.boundingBoxCoordinates={x:0,y:0},e.boundingBoxDimensions=s,e.boundingBoxScaleMethod==="auto"){const a=pa(s);e.scaledBoundingBoxDimensions=a}}},resetCanvasView:(e,t)=>{const{contentRect:n,shouldScaleTo1:r}=t.payload,{stageDimensions:{width:i,height:o}}=e,{x:s,y:a,width:l,height:u}=n;if(l!==0&&u!==0){const c=r?1:Nl(i,o,l,u,Vc),d=Ml(i,o,s,a,l,u,c);e.stageScale=c,e.stageCoordinates=d}else{const c=Nl(i,o,512,512,Vc),d=Ml(i,o,0,0,512,512,c),f={width:512,height:512};if(e.stageScale=c,e.stageCoordinates=d,e.boundingBoxCoordinates={x:0,y:0},e.boundingBoxDimensions=f,e.boundingBoxScaleMethod==="auto"){const h=pa(f);e.scaledBoundingBoxDimensions=h}}},nextStagingAreaImage:e=>{if(!e.layerState.stagingArea.images.length)return;const t=e.layerState.stagingArea.selectedImageIndex,n=e.layerState.stagingArea.images.length;e.layerState.stagingArea.selectedImageIndex=Math.min(t+1,n-1)},prevStagingAreaImage:e=>{if(!e.layerState.stagingArea.images.length)return;const t=e.layerState.stagingArea.selectedImageIndex;e.layerState.stagingArea.selectedImageIndex=Math.max(t-1,0)},commitStagingAreaImage:(e,t)=>{if(!e.layerState.stagingArea.images.length)return;const{images:n,selectedImageIndex:r}=e.layerState.stagingArea;e.pastLayerStates.push(Ln(e.layerState)),e.pastLayerStates.length>e.maxHistory&&e.pastLayerStates.shift(),e.layerState.objects.push({...n[r]}),e.layerState.stagingArea={...Kl.stagingArea},e.futureLayerStates=[],e.shouldShowStagingOutline=!0,e.shouldShowStagingImage=!0},fitBoundingBoxToStage:e=>{const{boundingBoxDimensions:t,boundingBoxCoordinates:n,stageDimensions:r,stageScale:i}=e,o=r.width/i,s=r.height/i;if(n.x<0||n.x+t.width>o||n.y<0||n.y+t.height>s){const a={width:hp(Ss(o,64,512),64),height:hp(Ss(s,64,512),64)},l={x:Ui(o/2-a.width/2,64),y:Ui(s/2-a.height/2,64)};if(e.boundingBoxDimensions=a,e.boundingBoxCoordinates=l,e.boundingBoxScaleMethod==="auto"){const u=pa(a);e.scaledBoundingBoxDimensions=u}}},setBoundingBoxScaleMethod:(e,t)=>{if(e.boundingBoxScaleMethod=t.payload,t.payload==="auto"){const n=pa(e.boundingBoxDimensions);e.scaledBoundingBoxDimensions=n}},setScaledBoundingBoxDimensions:(e,t)=>{e.scaledBoundingBoxDimensions=t.payload},setShouldShowStagingImage:(e,t)=>{e.shouldShowStagingImage=t.payload},setShouldShowStagingOutline:(e,t)=>{e.shouldShowStagingOutline=t.payload},setShouldShowCanvasDebugInfo:(e,t)=>{e.shouldShowCanvasDebugInfo=t.payload},setShouldRestrictStrokesToBox:(e,t)=>{e.shouldRestrictStrokesToBox=t.payload},setShouldAntialias:(e,t)=>{e.shouldAntialias=t.payload},setShouldCropToBoundingBoxOnSave:(e,t)=>{e.shouldCropToBoundingBoxOnSave=t.payload},setColorPickerColor:(e,t)=>{e.colorPickerColor=t.payload},commitColorPickerColor:e=>{e.brushColor={...e.colorPickerColor,a:e.brushColor.a},e.tool="brush"},setMergedCanvas:(e,t)=>{e.pastLayerStates.push(Ln(e.layerState)),e.futureLayerStates=[],e.layerState.objects=[t.payload]},resetCanvasInteractionState:e=>{e.cursorPosition=null,e.isDrawing=!1,e.isMouseOverBoundingBox=!1,e.isMoveBoundingBoxKeyHeld=!1,e.isMoveStageKeyHeld=!1,e.isMovingBoundingBox=!1,e.isMovingStage=!1,e.isTransformingBoundingBox=!1},mouseLeftCanvas:e=>{e.cursorPosition=null,e.isDrawing=!1,e.isMouseOverBoundingBox=!1,e.isMovingBoundingBox=!1,e.isTransformingBoundingBox=!1}},extraReducers:e=>{e.addCase(hl.pending,t=>{t.layerState.stagingArea.images.length||(t.layerState.stagingArea=Kl.stagingArea)}),e.addCase(_Q,t=>{t.doesCanvasNeedScaling=!0}),e.addCase(RR,t=>{t.doesCanvasNeedScaling=!0}),e.addCase(bQ,(t,n)=>{const r=n.payload;r&&(t.boundingBoxDimensions.height=Ui(t.boundingBoxDimensions.width/r,64))})}}),{addEraseRect:Dxe,addFillRect:Lxe,addImageToStagingArea:$Q,addLine:$xe,addPointToCurrentLine:Fxe,clearCanvasHistory:Bxe,clearMask:jxe,commitColorPickerColor:Vxe,commitStagingAreaImage:FQ,discardStagedImages:zxe,fitBoundingBoxToStage:Uxe,mouseLeftCanvas:Gxe,nextStagingAreaImage:Hxe,prevStagingAreaImage:qxe,redo:Wxe,resetCanvas:LR,resetCanvasInteractionState:Kxe,resetCanvasView:Xxe,resizeAndScaleCanvas:Yxe,resizeCanvas:Qxe,setBoundingBoxCoordinates:Zxe,setBoundingBoxDimensions:Jxe,setBoundingBoxPreviewFill:eCe,setBoundingBoxScaleMethod:tCe,flipBoundingBoxAxes:nCe,setBrushColor:rCe,setBrushSize:iCe,setCanvasContainerDimensions:oCe,setColorPickerColor:sCe,setCursorPosition:aCe,setDoesCanvasNeedScaling:lCe,setInitialCanvasImage:$R,setIsDrawing:uCe,setIsMaskEnabled:cCe,setIsMouseOverBoundingBox:dCe,setIsMoveBoundingBoxKeyHeld:fCe,setIsMoveStageKeyHeld:hCe,setIsMovingBoundingBox:pCe,setIsMovingStage:gCe,setIsTransformingBoundingBox:mCe,setLayer:yCe,setMaskColor:vCe,setMergedCanvas:BQ,setShouldAutoSave:bCe,setShouldCropToBoundingBoxOnSave:SCe,setShouldDarkenOutsideBoundingBox:_Ce,setShouldLockBoundingBox:wCe,setShouldPreserveMaskedArea:xCe,setShouldShowBoundingBox:CCe,setShouldShowBrush:TCe,setShouldShowBrushPreview:ECe,setShouldShowCanvasDebugInfo:PCe,setShouldShowCheckboardTransparency:ACe,setShouldShowGrid:kCe,setShouldShowIntermediates:OCe,setShouldShowStagingImage:RCe,setShouldShowStagingOutline:ICe,setShouldSnapToGrid:MCe,setStageCoordinates:NCe,setStageScale:DCe,setTool:LCe,toggleShouldLockBoundingBox:$Ce,toggleTool:FCe,undo:BCe,setScaledBoundingBoxDimensions:jCe,setShouldRestrictStrokesToBox:VCe,stagingAreaInitialized:jQ,canvasSessionIdChanged:VQ,setShouldAntialias:zCe}=DR.actions,zQ=DR.reducer,UQ=(e,t)=>{const n=new Date(e),r=new Date(t);return n>r?1:ne==null,YQ=e=>encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),$_=Symbol("encodeFragmentIdentifier");function QQ(e){switch(e.arrayFormat){case"index":return t=>(n,r)=>{const i=n.length;return r===void 0||e.skipNull&&r===null||e.skipEmptyString&&r===""?n:r===null?[...n,[qt(t,e),"[",i,"]"].join("")]:[...n,[qt(t,e),"[",qt(i,e),"]=",qt(r,e)].join("")]};case"bracket":return t=>(n,r)=>r===void 0||e.skipNull&&r===null||e.skipEmptyString&&r===""?n:r===null?[...n,[qt(t,e),"[]"].join("")]:[...n,[qt(t,e),"[]=",qt(r,e)].join("")];case"colon-list-separator":return t=>(n,r)=>r===void 0||e.skipNull&&r===null||e.skipEmptyString&&r===""?n:r===null?[...n,[qt(t,e),":list="].join("")]:[...n,[qt(t,e),":list=",qt(r,e)].join("")];case"comma":case"separator":case"bracket-separator":{const t=e.arrayFormat==="bracket-separator"?"[]=":"=";return n=>(r,i)=>i===void 0||e.skipNull&&i===null||e.skipEmptyString&&i===""?r:(i=i===null?"":i,r.length===0?[[qt(n,e),t,qt(i,e)].join("")]:[[r,qt(i,e)].join(e.arrayFormatSeparator)])}default:return t=>(n,r)=>r===void 0||e.skipNull&&r===null||e.skipEmptyString&&r===""?n:r===null?[...n,qt(t,e)]:[...n,[qt(t,e),"=",qt(r,e)].join("")]}}function ZQ(e){let t;switch(e.arrayFormat){case"index":return(n,r,i)=>{if(t=/\[(\d*)]$/.exec(n),n=n.replace(/\[\d*]$/,""),!t){i[n]=r;return}i[n]===void 0&&(i[n]={}),i[n][t[1]]=r};case"bracket":return(n,r,i)=>{if(t=/(\[])$/.exec(n),n=n.replace(/\[]$/,""),!t){i[n]=r;return}if(i[n]===void 0){i[n]=[r];return}i[n]=[...i[n],r]};case"colon-list-separator":return(n,r,i)=>{if(t=/(:list)$/.exec(n),n=n.replace(/:list$/,""),!t){i[n]=r;return}if(i[n]===void 0){i[n]=[r];return}i[n]=[...i[n],r]};case"comma":case"separator":return(n,r,i)=>{const o=typeof r=="string"&&r.includes(e.arrayFormatSeparator),s=typeof r=="string"&&!o&&wo(r,e).includes(e.arrayFormatSeparator);r=s?wo(r,e):r;const a=o||s?r.split(e.arrayFormatSeparator).map(l=>wo(l,e)):r===null?r:wo(r,e);i[n]=a};case"bracket-separator":return(n,r,i)=>{const o=/(\[])$/.test(n);if(n=n.replace(/\[]$/,""),!o){i[n]=r&&wo(r,e);return}const s=r===null?[]:r.split(e.arrayFormatSeparator).map(a=>wo(a,e));if(i[n]===void 0){i[n]=s;return}i[n]=[...i[n],...s]};default:return(n,r,i)=>{if(i[n]===void 0){i[n]=r;return}i[n]=[...[i[n]].flat(),r]}}}function jR(e){if(typeof e!="string"||e.length!==1)throw new TypeError("arrayFormatSeparator must be single character string")}function qt(e,t){return t.encode?t.strict?YQ(e):encodeURIComponent(e):e}function wo(e,t){return t.decode?WQ(e):e}function VR(e){return Array.isArray(e)?e.sort():typeof e=="object"?VR(Object.keys(e)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]):e}function zR(e){const t=e.indexOf("#");return t!==-1&&(e=e.slice(0,t)),e}function JQ(e){let t="";const n=e.indexOf("#");return n!==-1&&(t=e.slice(n)),t}function J4(e,t){return t.parseNumbers&&!Number.isNaN(Number(e))&&typeof e=="string"&&e.trim()!==""?e=Number(e):t.parseBooleans&&e!==null&&(e.toLowerCase()==="true"||e.toLowerCase()==="false")&&(e=e.toLowerCase()==="true"),e}function $x(e){e=zR(e);const t=e.indexOf("?");return t===-1?"":e.slice(t+1)}function Fx(e,t){t={decode:!0,sort:!0,arrayFormat:"none",arrayFormatSeparator:",",parseNumbers:!1,parseBooleans:!1,...t},jR(t.arrayFormatSeparator);const n=ZQ(t),r=Object.create(null);if(typeof e!="string"||(e=e.trim().replace(/^[?#&]/,""),!e))return r;for(const i of e.split("&")){if(i==="")continue;const o=t.decode?i.replace(/\+/g," "):i;let[s,a]=BR(o,"=");s===void 0&&(s=o),a=a===void 0?null:["comma","separator","bracket-separator"].includes(t.arrayFormat)?a:wo(a,t),n(wo(s,t),a,r)}for(const[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(const[s,a]of Object.entries(o))o[s]=J4(a,t);else r[i]=J4(o,t);return t.sort===!1?r:(t.sort===!0?Object.keys(r).sort():Object.keys(r).sort(t.sort)).reduce((i,o)=>{const s=r[o];return s&&typeof s=="object"&&!Array.isArray(s)?i[o]=VR(s):i[o]=s,i},Object.create(null))}function UR(e,t){if(!e)return"";t={encode:!0,strict:!0,arrayFormat:"none",arrayFormatSeparator:",",...t},jR(t.arrayFormatSeparator);const n=s=>t.skipNull&&XQ(e[s])||t.skipEmptyString&&e[s]==="",r=QQ(t),i={};for(const[s,a]of Object.entries(e))n(s)||(i[s]=a);const o=Object.keys(i);return t.sort!==!1&&o.sort(t.sort),o.map(s=>{const a=e[s];return a===void 0?"":a===null?qt(s,t):Array.isArray(a)?a.length===0&&t.arrayFormat==="bracket-separator"?qt(s,t)+"[]":a.reduce(r(s),[]).join("&"):qt(s,t)+"="+qt(a,t)}).filter(s=>s.length>0).join("&")}function GR(e,t){var i;t={decode:!0,...t};let[n,r]=BR(e,"#");return n===void 0&&(n=e),{url:((i=n==null?void 0:n.split("?"))==null?void 0:i[0])??"",query:Fx($x(e),t),...t&&t.parseFragmentIdentifier&&r?{fragmentIdentifier:wo(r,t)}:{}}}function HR(e,t){t={encode:!0,strict:!0,[$_]:!0,...t};const n=zR(e.url).split("?")[0]||"",r=$x(e.url),i={...Fx(r,{sort:!1}),...e.query};let o=UR(i,t);o&&(o=`?${o}`);let s=JQ(e.url);if(e.fragmentIdentifier){const a=new URL(n);a.hash=e.fragmentIdentifier,s=t[$_]?a.hash:`#${e.fragmentIdentifier}`}return`${n}${o}${s}`}function qR(e,t,n){n={parseFragmentIdentifier:!0,[$_]:!1,...n};const{url:r,query:i,fragmentIdentifier:o}=GR(e,n);return HR({url:r,query:KQ(i,t),fragmentIdentifier:o},n)}function eZ(e,t,n){const r=Array.isArray(t)?i=>!t.includes(i):(i,o)=>!t(i,o);return qR(e,r,n)}const F_=Object.freeze(Object.defineProperty({__proto__:null,exclude:eZ,extract:$x,parse:Fx,parseUrl:GR,pick:qR,stringify:UR,stringifyUrl:HR},Symbol.toStringTag,{value:"Module"}));var xm=globalThis&&globalThis.__generator||function(e,t){var n={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,i,o,s;return s={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(u){return function(c){return l([u,c])}}function l(u){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(o=u[0]&2?i.return:u[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,u[1])).done)return o;switch(i=0,o&&(u=[u[0]&2,o.value]),u[0]){case 0:case 1:o=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,i=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(o=n.trys,!(o=o.length>0&&o[o.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!o||u[1]>o[0]&&u[1]"u"||navigator.onLine===void 0?!0:navigator.onLine}function cZ(){return typeof document>"u"?!0:document.visibilityState!=="hidden"}var rT=xi;function XR(e,t){if(e===t||!(rT(e)&&rT(t)||Array.isArray(e)&&Array.isArray(t)))return t;for(var n=Object.keys(t),r=Object.keys(e),i=n.length===r.length,o=Array.isArray(t)?[]:{},s=0,a=n;s=200&&e.status<=299},fZ=function(e){return/ion\/(vnd\.api\+)?json/.test(e.get("content-type")||"")};function oT(e){if(!xi(e))return e;for(var t=$t({},e),n=0,r=Object.entries(t);n"u"&&a===iT&&console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments."),function(g,b){return Em(t,null,function(){var _,w,x,T,P,E,A,$,M,C,O,I,N,R,D,L,j,U,G,W,X,Y,B,H,Q,J,ne,te,xe,ve,ce,Ne,se,gt,vn,It;return xm(this,function(ut){switch(ut.label){case 0:return _=b.signal,w=b.getState,x=b.extra,T=b.endpoint,P=b.forced,E=b.type,$=typeof g=="string"?{url:g}:g,M=$.url,C=$.headers,O=C===void 0?new Headers(v.headers):C,I=$.params,N=I===void 0?void 0:I,R=$.responseHandler,D=R===void 0?m??"json":R,L=$.validateStatus,j=L===void 0?S??dZ:L,U=$.timeout,G=U===void 0?p:U,W=tT($,["url","headers","params","responseHandler","validateStatus","timeout"]),X=$t(Hi($t({},v),{signal:_}),W),O=new Headers(oT(O)),Y=X,[4,o(O,{getState:w,extra:x,endpoint:T,forced:P,type:E})];case 1:Y.headers=ut.sent()||O,B=function(Je){return typeof Je=="object"&&(xi(Je)||Array.isArray(Je)||typeof Je.toJSON=="function")},!X.headers.has("content-type")&&B(X.body)&&X.headers.set("content-type",f),B(X.body)&&c(X.headers)&&(X.body=JSON.stringify(X.body,h)),N&&(H=~M.indexOf("?")?"&":"?",Q=l?l(N):new URLSearchParams(oT(N)),M+=H+Q),M=lZ(r,M),J=new Request(M,X),ne=J.clone(),A={request:ne},xe=!1,ve=G&&setTimeout(function(){xe=!0,b.abort()},G),ut.label=2;case 2:return ut.trys.push([2,4,5,6]),[4,a(J)];case 3:return te=ut.sent(),[3,6];case 4:return ce=ut.sent(),[2,{error:{status:xe?"TIMEOUT_ERROR":"FETCH_ERROR",error:String(ce)},meta:A}];case 5:return ve&&clearTimeout(ve),[7];case 6:Ne=te.clone(),A.response=Ne,gt="",ut.label=7;case 7:return ut.trys.push([7,9,,10]),[4,Promise.all([y(te,D).then(function(Je){return se=Je},function(Je){return vn=Je}),Ne.text().then(function(Je){return gt=Je},function(){})])];case 8:if(ut.sent(),vn)throw vn;return[3,10];case 9:return It=ut.sent(),[2,{error:{status:"PARSING_ERROR",originalStatus:te.status,data:gt,error:String(It)},meta:A}];case 10:return[2,j(te,se)?{data:se,meta:A}:{error:{status:te.status,data:se},meta:A}]}})})};function y(g,b){return Em(this,null,function(){var _;return xm(this,function(w){switch(w.label){case 0:return typeof b=="function"?[2,b(g)]:(b==="content-type"&&(b=c(g.headers)?"json":"text"),b!=="json"?[3,2]:[4,g.text()]);case 1:return _=w.sent(),[2,_.length?JSON.parse(_):null];case 2:return[2,g.text()]}})})}}var sT=function(){function e(t,n){n===void 0&&(n=void 0),this.value=t,this.meta=n}return e}(),Bx=ue("__rtkq/focused"),YR=ue("__rtkq/unfocused"),jx=ue("__rtkq/online"),QR=ue("__rtkq/offline"),no;(function(e){e.query="query",e.mutation="mutation"})(no||(no={}));function ZR(e){return e.type===no.query}function pZ(e){return e.type===no.mutation}function JR(e,t,n,r,i,o){return gZ(e)?e(t,n,r,i).map(B_).map(o):Array.isArray(e)?e.map(B_).map(o):[]}function gZ(e){return typeof e=="function"}function B_(e){return typeof e=="string"?{type:e}:e}function yb(e){return e!=null}var Ef=Symbol("forceQueryFn"),j_=function(e){return typeof e[Ef]=="function"};function mZ(e){var t=e.serializeQueryArgs,n=e.queryThunk,r=e.mutationThunk,i=e.api,o=e.context,s=new Map,a=new Map,l=i.internalActions,u=l.unsubscribeQueryResult,c=l.removeMutationResult,d=l.updateSubscriptionOptions;return{buildInitiateQuery:y,buildInitiateMutation:g,getRunningQueryThunk:p,getRunningMutationThunk:m,getRunningQueriesThunk:S,getRunningMutationsThunk:v,getRunningOperationPromises:h,removalWarning:f};function f(){throw new Error(`This method had to be removed due to a conceptual bug in RTK. + Please see https://github.com/reduxjs/redux-toolkit/pull/2481 for details. + See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for new guidance on SSR.`)}function h(){typeof process<"u";var b=function(_){return Array.from(_.values()).flatMap(function(w){return w?Object.values(w):[]})};return Cm(Cm([],b(s)),b(a)).filter(yb)}function p(b,_){return function(w){var x,T=o.endpointDefinitions[b],P=t({queryArgs:_,endpointDefinition:T,endpointName:b});return(x=s.get(w))==null?void 0:x[P]}}function m(b,_){return function(w){var x;return(x=a.get(w))==null?void 0:x[_]}}function S(){return function(b){return Object.values(s.get(b)||{}).filter(yb)}}function v(){return function(b){return Object.values(a.get(b)||{}).filter(yb)}}function y(b,_){var w=function(x,T){var P=T===void 0?{}:T,E=P.subscribe,A=E===void 0?!0:E,$=P.forceRefetch,M=P.subscriptionOptions,C=Ef,O=P[C];return function(I,N){var R,D,L=t({queryArgs:x,endpointDefinition:_,endpointName:b}),j=n((R={type:"query",subscribe:A,forceRefetch:$,subscriptionOptions:M,endpointName:b,originalArgs:x,queryCacheKey:L},R[Ef]=O,R)),U=i.endpoints[b].select(x),G=I(j),W=U(N()),X=G.requestId,Y=G.abort,B=W.requestId!==X,H=(D=s.get(I))==null?void 0:D[L],Q=function(){return U(N())},J=Object.assign(O?G.then(Q):B&&!H?Promise.resolve(W):Promise.all([H,G]).then(Q),{arg:x,requestId:X,subscriptionOptions:M,queryCacheKey:L,abort:Y,unwrap:function(){return Em(this,null,function(){var te;return xm(this,function(xe){switch(xe.label){case 0:return[4,J];case 1:if(te=xe.sent(),te.isError)throw te.error;return[2,te.data]}})})},refetch:function(){return I(w(x,{subscribe:!1,forceRefetch:!0}))},unsubscribe:function(){A&&I(u({queryCacheKey:L,requestId:X}))},updateSubscriptionOptions:function(te){J.subscriptionOptions=te,I(d({endpointName:b,requestId:X,queryCacheKey:L,options:te}))}});if(!H&&!B&&!O){var ne=s.get(I)||{};ne[L]=J,s.set(I,ne),J.then(function(){delete ne[L],Object.keys(ne).length||s.delete(I)})}return J}};return w}function g(b){return function(_,w){var x=w===void 0?{}:w,T=x.track,P=T===void 0?!0:T,E=x.fixedCacheKey;return function(A,$){var M=r({type:"mutation",endpointName:b,originalArgs:_,track:P,fixedCacheKey:E}),C=A(M),O=C.requestId,I=C.abort,N=C.unwrap,R=C.unwrap().then(function(U){return{data:U}}).catch(function(U){return{error:U}}),D=function(){A(c({requestId:O,fixedCacheKey:E}))},L=Object.assign(R,{arg:C.arg,requestId:O,abort:I,unwrap:N,unsubscribe:D,reset:D}),j=a.get(A)||{};return a.set(A,j),j[O]=L,L.then(function(){delete j[O],Object.keys(j).length||a.delete(A)}),E&&(j[E]=L,L.then(function(){j[E]===L&&(delete j[E],Object.keys(j).length||a.delete(A))})),L}}}}function aT(e){return e}function yZ(e){var t=this,n=e.reducerPath,r=e.baseQuery,i=e.context.endpointDefinitions,o=e.serializeQueryArgs,s=e.api,a=function(g,b,_){return function(w){var x=i[g];w(s.internalActions.queryResultPatched({queryCacheKey:o({queryArgs:b,endpointDefinition:x,endpointName:g}),patches:_}))}},l=function(g,b,_){return function(w,x){var T,P,E=s.endpoints[g].select(b)(x()),A={patches:[],inversePatches:[],undo:function(){return w(s.util.patchQueryData(g,b,A.inversePatches))}};if(E.status===vt.uninitialized)return A;if("data"in E)if(yr(E.data)){var $=gx(E.data,_),M=$[1],C=$[2];(T=A.patches).push.apply(T,M),(P=A.inversePatches).push.apply(P,C)}else{var O=_(E.data);A.patches.push({op:"replace",path:[],value:O}),A.inversePatches.push({op:"replace",path:[],value:E.data})}return w(s.util.patchQueryData(g,b,A.patches)),A}},u=function(g,b,_){return function(w){var x;return w(s.endpoints[g].initiate(b,(x={subscribe:!1,forceRefetch:!0},x[Ef]=function(){return{data:_}},x)))}},c=function(g,b){return Em(t,[g,b],function(_,w){var x,T,P,E,A,$,M,C,O,I,N,R,D,L,j,U,G,W,X=w.signal,Y=w.abort,B=w.rejectWithValue,H=w.fulfillWithValue,Q=w.dispatch,J=w.getState,ne=w.extra;return xm(this,function(te){switch(te.label){case 0:x=i[_.endpointName],te.label=1;case 1:return te.trys.push([1,8,,13]),T=aT,P=void 0,E={signal:X,abort:Y,dispatch:Q,getState:J,extra:ne,endpoint:_.endpointName,type:_.type,forced:_.type==="query"?d(_,J()):void 0},A=_.type==="query"?_[Ef]:void 0,A?(P=A(),[3,6]):[3,2];case 2:return x.query?[4,r(x.query(_.originalArgs),E,x.extraOptions)]:[3,4];case 3:return P=te.sent(),x.transformResponse&&(T=x.transformResponse),[3,6];case 4:return[4,x.queryFn(_.originalArgs,E,x.extraOptions,function(xe){return r(xe,E,x.extraOptions)})];case 5:P=te.sent(),te.label=6;case 6:if(typeof process<"u",P.error)throw new sT(P.error,P.meta);return N=H,[4,T(P.data,P.meta,_.originalArgs)];case 7:return[2,N.apply(void 0,[te.sent(),(G={fulfilledTimeStamp:Date.now(),baseQueryMeta:P.meta},G[Ra]=!0,G)])];case 8:if(R=te.sent(),D=R,!(D instanceof sT))return[3,12];L=aT,x.query&&x.transformErrorResponse&&(L=x.transformErrorResponse),te.label=9;case 9:return te.trys.push([9,11,,12]),j=B,[4,L(D.value,D.meta,_.originalArgs)];case 10:return[2,j.apply(void 0,[te.sent(),(W={baseQueryMeta:D.meta},W[Ra]=!0,W)])];case 11:return U=te.sent(),D=U,[3,12];case 12:throw typeof process<"u",console.error(D),D;case 13:return[2]}})})};function d(g,b){var _,w,x,T,P=(w=(_=b[n])==null?void 0:_.queries)==null?void 0:w[g.queryCacheKey],E=(x=b[n])==null?void 0:x.config.refetchOnMountOrArgChange,A=P==null?void 0:P.fulfilledTimeStamp,$=(T=g.forceRefetch)!=null?T:g.subscribe&&E;return $?$===!0||(Number(new Date)-Number(A))/1e3>=$:!1}var f=Vs(n+"/executeQuery",c,{getPendingMeta:function(){var g;return g={startedTimeStamp:Date.now()},g[Ra]=!0,g},condition:function(g,b){var _=b.getState,w,x,T,P=_(),E=(x=(w=P[n])==null?void 0:w.queries)==null?void 0:x[g.queryCacheKey],A=E==null?void 0:E.fulfilledTimeStamp,$=g.originalArgs,M=E==null?void 0:E.originalArgs,C=i[g.endpointName];return j_(g)?!0:(E==null?void 0:E.status)==="pending"?!1:d(g,P)||ZR(C)&&((T=C==null?void 0:C.forceRefetch)!=null&&T.call(C,{currentArg:$,previousArg:M,endpointState:E,state:P}))?!0:!A},dispatchConditionRejection:!0}),h=Vs(n+"/executeMutation",c,{getPendingMeta:function(){var g;return g={startedTimeStamp:Date.now()},g[Ra]=!0,g}}),p=function(g){return"force"in g},m=function(g){return"ifOlderThan"in g},S=function(g,b,_){return function(w,x){var T=p(_)&&_.force,P=m(_)&&_.ifOlderThan,E=function(C){return C===void 0&&(C=!0),s.endpoints[g].initiate(b,{forceRefetch:C})},A=s.endpoints[g].select(b)(x());if(T)w(E());else if(P){var $=A==null?void 0:A.fulfilledTimeStamp;if(!$){w(E());return}var M=(Number(new Date)-Number(new Date($)))/1e3>=P;M&&w(E())}else w(E(!1))}};function v(g){return function(b){var _,w;return((w=(_=b==null?void 0:b.meta)==null?void 0:_.arg)==null?void 0:w.endpointName)===g}}function y(g,b){return{matchPending:Tu(u0(g),v(b)),matchFulfilled:Tu(ea(g),v(b)),matchRejected:Tu(Xu(g),v(b))}}return{queryThunk:f,mutationThunk:h,prefetch:S,updateQueryData:l,upsertQueryData:u,patchQueryData:a,buildMatchThunkActions:y}}function e7(e,t,n,r){return JR(n[e.meta.arg.endpointName][t],ea(e)?e.payload:void 0,uh(e)?e.payload:void 0,e.meta.arg.originalArgs,"baseQueryMeta"in e.meta?e.meta.baseQueryMeta:void 0,r)}function yp(e,t,n){var r=e[t];r&&n(r)}function Pf(e){var t;return(t="arg"in e?e.arg.fixedCacheKey:e.fixedCacheKey)!=null?t:e.requestId}function lT(e,t,n){var r=e[Pf(t)];r&&n(r)}var zc={};function vZ(e){var t=e.reducerPath,n=e.queryThunk,r=e.mutationThunk,i=e.context,o=i.endpointDefinitions,s=i.apiUid,a=i.extractRehydrationInfo,l=i.hasRehydrationInfo,u=e.assertTagType,c=e.config,d=ue(t+"/resetApiState"),f=Pt({name:t+"/queries",initialState:zc,reducers:{removeQueryResult:{reducer:function(_,w){var x=w.payload.queryCacheKey;delete _[x]},prepare:cg()},queryResultPatched:function(_,w){var x=w.payload,T=x.queryCacheKey,P=x.patches;yp(_,T,function(E){E.data=v_(E.data,P.concat())})}},extraReducers:function(_){_.addCase(n.pending,function(w,x){var T=x.meta,P=x.meta.arg,E,A,$=j_(P);(P.subscribe||$)&&((A=w[E=P.queryCacheKey])!=null||(w[E]={status:vt.uninitialized,endpointName:P.endpointName})),yp(w,P.queryCacheKey,function(M){M.status=vt.pending,M.requestId=$&&M.requestId?M.requestId:T.requestId,P.originalArgs!==void 0&&(M.originalArgs=P.originalArgs),M.startedTimeStamp=T.startedTimeStamp})}).addCase(n.fulfilled,function(w,x){var T=x.meta,P=x.payload;yp(w,T.arg.queryCacheKey,function(E){var A;if(!(E.requestId!==T.requestId&&!j_(T.arg))){var $=o[T.arg.endpointName].merge;if(E.status=vt.fulfilled,$)if(E.data!==void 0){var M=T.fulfilledTimeStamp,C=T.arg,O=T.baseQueryMeta,I=T.requestId,N=Js(E.data,function(R){return $(R,P,{arg:C.originalArgs,baseQueryMeta:O,fulfilledTimeStamp:M,requestId:I})});E.data=N}else E.data=P;else E.data=(A=o[T.arg.endpointName].structuralSharing)==null||A?XR(er(E.data)?lx(E.data):E.data,P):P;delete E.error,E.fulfilledTimeStamp=T.fulfilledTimeStamp}})}).addCase(n.rejected,function(w,x){var T=x.meta,P=T.condition,E=T.arg,A=T.requestId,$=x.error,M=x.payload;yp(w,E.queryCacheKey,function(C){if(!P){if(C.requestId!==A)return;C.status=vt.rejected,C.error=M??$}})}).addMatcher(l,function(w,x){for(var T=a(x).queries,P=0,E=Object.entries(T);P{const r=Tf.get(),i=Cf.get();return hZ({baseUrl:`${r??""}/api/v1`,prepareHeaders:s=>(i&&s.set("Authorization",`Bearer ${i}`),s)})(e,t,n)},Hs=XZ({baseQuery:QZ,reducerPath:"api",tagTypes:YZ,endpoints:()=>({})}),_b=(e,t)=>{if(!e)return!1;const n=V_.selectAll(e);if(n.length>1){const r=new Date(t.created_at),i=new Date(n[n.length-1].created_at);return r>=i}else if([0,1].includes(n.length))return!0;return!1},Uc=e=>gi.includes(e.image_category)?gi:_s,Kn=cl({selectId:e=>e.image_name,sortComparer:(e,t)=>UQ(t.updated_at,e.updated_at)}),V_=Kn.getSelectors(),di=e=>`images/?${F_.stringify(e,{arrayFormat:"none"})}`,he=Hs.injectEndpoints({endpoints:e=>({listImages:e.query({query:t=>({url:di(t),method:"GET"}),providesTags:(t,n,{board_id:r,categories:i})=>[{type:"ImageList",id:di({board_id:r,categories:i})}],serializeQueryArgs:({queryArgs:t})=>{const{board_id:n,categories:r}=t;return di({board_id:n,categories:r})},transformResponse(t){const{total:n,items:r}=t;return Kn.addMany(Kn.getInitialState({total:n}),r)},merge:(t,n)=>{Kn.addMany(t,V_.selectAll(n)),t.total=n.total},forceRefetch({currentArg:t,previousArg:n}){return(t==null?void 0:t.offset)!==(n==null?void 0:n.offset)},async onQueryStarted(t,{dispatch:n,queryFulfilled:r}){try{const{data:i}=await r;V_.selectAll(i).forEach(o=>{n(he.util.upsertQueryData("getImageDTO",o.image_name,o))})}catch{}},keepUnusedDataFor:86400}),getIntermediatesCount:e.query({query:()=>({url:di({is_intermediate:!0})}),providesTags:["IntermediatesCount"],transformResponse:t=>t.total}),getImageDTO:e.query({query:t=>({url:`images/${t}`}),providesTags:(t,n,r)=>{const i=[{type:"Image",id:r}];return t!=null&&t.board_id&&i.push({type:"Board",id:t.board_id}),i},keepUnusedDataFor:86400}),getImageMetadata:e.query({query:t=>({url:`images/${t}/metadata`}),providesTags:(t,n,r)=>[{type:"ImageMetadata",id:r}],keepUnusedDataFor:86400}),getBoardImagesTotal:e.query({query:t=>({url:di({board_id:t??"none",categories:gi,is_intermediate:!1,limit:0,offset:0}),method:"GET"}),providesTags:(t,n,r)=>[{type:"BoardImagesTotal",id:r??"none"}],transformResponse:t=>t.total}),getBoardAssetsTotal:e.query({query:t=>({url:di({board_id:t??"none",categories:_s,is_intermediate:!1,limit:0,offset:0}),method:"GET"}),providesTags:(t,n,r)=>[{type:"BoardAssetsTotal",id:r??"none"}],transformResponse:t=>t.total}),clearIntermediates:e.mutation({query:()=>({url:"images/clear-intermediates",method:"POST"}),invalidatesTags:["IntermediatesCount"]}),deleteImage:e.mutation({query:({image_name:t})=>({url:`images/${t}`,method:"DELETE"}),invalidatesTags:(t,n,{board_id:r})=>[{type:"BoardImagesTotal",id:r??"none"},{type:"BoardAssetsTotal",id:r??"none"}],async onQueryStarted(t,{dispatch:n,queryFulfilled:r}){const{image_name:i,board_id:o}=t,s=[],a=Uc(t);s.push(n(he.util.updateQueryData("listImages",{board_id:o??"none",categories:a},l=>{const u=l.total,d=Kn.removeOne(l,i).total-u;l.total=l.total+d})));try{await r}catch{s.forEach(l=>l.undo())}}}),changeImageIsIntermediate:e.mutation({query:({imageDTO:t,is_intermediate:n})=>({url:`images/${t.image_name}`,method:"PATCH",body:{is_intermediate:n}}),invalidatesTags:(t,n,{imageDTO:r})=>[{type:"BoardImagesTotal",id:r.board_id??"none"},{type:"BoardAssetsTotal",id:r.board_id??"none"}],async onQueryStarted({imageDTO:t,is_intermediate:n},{dispatch:r,queryFulfilled:i,getState:o}){const s=[];s.push(r(he.util.updateQueryData("getImageDTO",t.image_name,l=>{Object.assign(l,{is_intermediate:n})})));const a=Uc(t);if(n)s.push(r(he.util.updateQueryData("listImages",{board_id:t.board_id??"none",categories:a},l=>{const u=l.total,d=Kn.removeOne(l,t.image_name).total-u;l.total=l.total+d})));else{console.log(t);const l={board_id:t.board_id??"none",categories:a},u=he.endpoints.listImages.select(l)(o()),c=u.data&&u.data.ids.length>=u.data.total,d=_b(u.data,t);(c||d)&&s.push(r(he.util.updateQueryData("listImages",l,f=>{const h=f.total,m=Kn.upsertOne(f,t).total-h;f.total=f.total+m})))}try{await i}catch{s.forEach(l=>l.undo())}}}),changeImageSessionId:e.mutation({query:({imageDTO:t,session_id:n})=>({url:`images/${t.image_name}`,method:"PATCH",body:{session_id:n}}),invalidatesTags:(t,n,{imageDTO:r})=>[{type:"BoardImagesTotal",id:r.board_id??"none"},{type:"BoardAssetsTotal",id:r.board_id??"none"}],async onQueryStarted({imageDTO:t,session_id:n},{dispatch:r,queryFulfilled:i,getState:o}){const s=[];s.push(r(he.util.updateQueryData("getImageDTO",t.image_name,a=>{Object.assign(a,{session_id:n})})));try{await i}catch{s.forEach(a=>a.undo())}}}),uploadImage:e.mutation({query:({file:t,image_category:n,is_intermediate:r,session_id:i,board_id:o,crop_visible:s})=>{const a=new FormData;return a.append("file",t),{url:"images/",method:"POST",body:a,params:{image_category:n,is_intermediate:r,session_id:i,board_id:o,crop_visible:s}}},async onQueryStarted({file:t,image_category:n,is_intermediate:r,postUploadAction:i,session_id:o,board_id:s},{dispatch:a,queryFulfilled:l}){try{const{data:u}=await l;if(u.is_intermediate)return;a(he.util.upsertQueryData("getImageDTO",u.image_name,u));const c=Uc(u);a(he.util.updateQueryData("listImages",{board_id:u.board_id??"none",categories:c},d=>{const f=d.total,p=Kn.addOne(d,u).total-f;d.total=d.total+p})),a(he.util.invalidateTags([{type:"BoardImagesTotal",id:u.board_id??"none"},{type:"BoardAssetsTotal",id:u.board_id??"none"}]))}catch{}}}),addImageToBoard:e.mutation({query:({board_id:t,imageDTO:n})=>{const{image_name:r}=n;return{url:"board_images/",method:"POST",body:{board_id:t,image_name:r}}},invalidatesTags:(t,n,{board_id:r,imageDTO:i})=>[{type:"Board",id:r},{type:"BoardImagesTotal",id:r},{type:"BoardImagesTotal",id:i.board_id??"none"},{type:"BoardAssetsTotal",id:r},{type:"BoardAssetsTotal",id:i.board_id??"none"}],async onQueryStarted({board_id:t,imageDTO:n},{dispatch:r,queryFulfilled:i,getState:o}){const s=[],a=Uc(n);if(s.push(r(he.util.updateQueryData("getImageDTO",n.image_name,l=>{Object.assign(l,{board_id:t})}))),!n.is_intermediate){s.push(r(he.util.updateQueryData("listImages",{board_id:n.board_id??"none",categories:a},f=>{const h=f.total,m=Kn.removeOne(f,n.image_name).total-h;f.total=f.total+m})));const l={board_id:t??"none",categories:a},u=he.endpoints.listImages.select(l)(o()),c=u.data&&u.data.ids.length>=u.data.total,d=_b(u.data,n);(c||d)&&s.push(r(he.util.updateQueryData("listImages",l,f=>{const h=f.total,m=Kn.addOne(f,n).total-h;f.total=f.total+m})))}try{await i}catch{s.forEach(l=>l.undo())}}}),removeImageFromBoard:e.mutation({query:({imageDTO:t})=>{const{board_id:n,image_name:r}=t;return{url:"board_images/",method:"DELETE",body:{board_id:n,image_name:r}}},invalidatesTags:(t,n,{imageDTO:r})=>[{type:"Board",id:r.board_id},{type:"BoardImagesTotal",id:r.board_id},{type:"BoardImagesTotal",id:"none"},{type:"BoardAssetsTotal",id:r.board_id},{type:"BoardAssetsTotal",id:"none"}],async onQueryStarted({imageDTO:t},{dispatch:n,queryFulfilled:r,getState:i}){const o=Uc(t),s=[];s.push(n(he.util.updateQueryData("getImageDTO",t.image_name,d=>{Object.assign(d,{board_id:void 0})}))),s.push(n(he.util.updateQueryData("listImages",{board_id:t.board_id??"none",categories:o},d=>{const f=d.total,p=Kn.removeOne(d,t.image_name).total-f;d.total=d.total+p})));const a={board_id:"none",categories:o},l=he.endpoints.listImages.select(a)(i()),u=l.data&&l.data.ids.length>=l.data.total,c=_b(l.data,t);(u||c)&&s.push(n(he.util.updateQueryData("listImages",a,d=>{const f=d.total,p=Kn.upsertOne(d,t).total-f;d.total=d.total+p})));try{await r}catch{s.forEach(d=>d.undo())}}})})}),{useGetIntermediatesCountQuery:GCe,useListImagesQuery:HCe,useLazyListImagesQuery:qCe,useGetImageDTOQuery:WCe,useGetImageMetadataQuery:KCe,useDeleteImageMutation:XCe,useGetBoardImagesTotalQuery:YCe,useGetBoardAssetsTotalQuery:QCe,useUploadImageMutation:ZCe,useAddImageToBoardMutation:JCe,useRemoveImageFromBoardMutation:e3e,useClearIntermediatesMutation:t3e}=he,n7=ue("socket/socketConnected"),r7=ue("socket/appSocketConnected"),i7=ue("socket/socketDisconnected"),o7=ue("socket/appSocketDisconnected"),Vx=ue("socket/socketSubscribed"),s7=ue("socket/appSocketSubscribed"),a7=ue("socket/socketUnsubscribed"),l7=ue("socket/appSocketUnsubscribed"),u7=ue("socket/socketInvocationStarted"),c7=ue("socket/appSocketInvocationStarted"),zx=ue("socket/socketInvocationComplete"),d7=ue("socket/appSocketInvocationComplete"),f7=ue("socket/socketInvocationError"),Ux=ue("socket/appSocketInvocationError"),h7=ue("socket/socketGraphExecutionStateComplete"),p7=ue("socket/appSocketGraphExecutionStateComplete"),g7=ue("socket/socketGeneratorProgress"),m7=ue("socket/appSocketGeneratorProgress"),y7=ue("socket/socketModelLoadStarted"),ZZ=ue("socket/appSocketModelLoadStarted"),v7=ue("socket/socketModelLoadCompleted"),JZ=ue("socket/appSocketModelLoadCompleted"),b7=ue("socket/socketSessionRetrievalError"),S7=ue("socket/appSocketSessionRetrievalError"),_7=ue("socket/socketInvocationRetrievalError"),w7=ue("socket/appSocketInvocationRetrievalError"),Gx=ue("controlNet/imageProcessed"),Xl={none:{type:"none",label:"none",description:"",default:{type:"none"}},canny_image_processor:{type:"canny_image_processor",label:"Canny",description:"",default:{id:"canny_image_processor",type:"canny_image_processor",low_threshold:100,high_threshold:200}},content_shuffle_image_processor:{type:"content_shuffle_image_processor",label:"Content Shuffle",description:"",default:{id:"content_shuffle_image_processor",type:"content_shuffle_image_processor",detect_resolution:512,image_resolution:512,h:512,w:512,f:256}},hed_image_processor:{type:"hed_image_processor",label:"HED",description:"",default:{id:"hed_image_processor",type:"hed_image_processor",detect_resolution:512,image_resolution:512,scribble:!1}},lineart_anime_image_processor:{type:"lineart_anime_image_processor",label:"Lineart Anime",description:"",default:{id:"lineart_anime_image_processor",type:"lineart_anime_image_processor",detect_resolution:512,image_resolution:512}},lineart_image_processor:{type:"lineart_image_processor",label:"Lineart",description:"",default:{id:"lineart_image_processor",type:"lineart_image_processor",detect_resolution:512,image_resolution:512,coarse:!1}},mediapipe_face_processor:{type:"mediapipe_face_processor",label:"Mediapipe Face",description:"",default:{id:"mediapipe_face_processor",type:"mediapipe_face_processor",max_faces:1,min_confidence:.5}},midas_depth_image_processor:{type:"midas_depth_image_processor",label:"Depth (Midas)",description:"",default:{id:"midas_depth_image_processor",type:"midas_depth_image_processor",a_mult:2,bg_th:.1}},mlsd_image_processor:{type:"mlsd_image_processor",label:"M-LSD",description:"",default:{id:"mlsd_image_processor",type:"mlsd_image_processor",detect_resolution:512,image_resolution:512,thr_d:.1,thr_v:.1}},normalbae_image_processor:{type:"normalbae_image_processor",label:"Normal BAE",description:"",default:{id:"normalbae_image_processor",type:"normalbae_image_processor",detect_resolution:512,image_resolution:512}},openpose_image_processor:{type:"openpose_image_processor",label:"Openpose",description:"",default:{id:"openpose_image_processor",type:"openpose_image_processor",detect_resolution:512,image_resolution:512,hand_and_face:!1}},pidi_image_processor:{type:"pidi_image_processor",label:"PIDI",description:"",default:{id:"pidi_image_processor",type:"pidi_image_processor",detect_resolution:512,image_resolution:512,scribble:!1,safe:!1}},zoe_depth_image_processor:{type:"zoe_depth_image_processor",label:"Depth (Zoe)",description:"",default:{id:"zoe_depth_image_processor",type:"zoe_depth_image_processor"}}},_p={canny:"canny_image_processor",mlsd:"mlsd_image_processor",depth:"midas_depth_image_processor",bae:"normalbae_image_processor",lineart:"lineart_image_processor",lineart_anime:"lineart_anime_image_processor",softedge:"hed_image_processor",shuffle:"content_shuffle_image_processor",openpose:"openpose_image_processor",mediapipe:"mediapipe_face_processor"},vT={isEnabled:!0,model:null,weight:1,beginStepPct:0,endStepPct:1,controlMode:"balanced",resizeMode:"just_resize",controlImage:null,processedControlImage:null,processorType:"canny_image_processor",processorNode:Xl.canny_image_processor.default,shouldAutoConfig:!0},z_={controlNets:{},isEnabled:!1,pendingControlImages:[]},x7=Pt({name:"controlNet",initialState:z_,reducers:{isControlNetEnabledToggled:e=>{e.isEnabled=!e.isEnabled},controlNetAdded:(e,t)=>{const{controlNetId:n,controlNet:r}=t.payload;e.controlNets[n]={...r??vT,controlNetId:n}},controlNetDuplicated:(e,t)=>{const{sourceControlNetId:n,newControlNetId:r}=t.payload,i=Ln(e.controlNets[n]);i.controlNetId=r,e.controlNets[r]=i},controlNetAddedFromImage:(e,t)=>{const{controlNetId:n,controlImage:r}=t.payload;e.controlNets[n]={...vT,controlNetId:n,controlImage:r}},controlNetRemoved:(e,t)=>{const{controlNetId:n}=t.payload;delete e.controlNets[n]},controlNetToggled:(e,t)=>{const{controlNetId:n}=t.payload;e.controlNets[n].isEnabled=!e.controlNets[n].isEnabled},controlNetImageChanged:(e,t)=>{const{controlNetId:n,controlImage:r}=t.payload;e.controlNets[n].controlImage=r,e.controlNets[n].processedControlImage=null,r!==null&&e.controlNets[n].processorType!=="none"&&e.pendingControlImages.push(n)},controlNetProcessedImageChanged:(e,t)=>{const{controlNetId:n,processedControlImage:r}=t.payload;e.controlNets[n].processedControlImage=r,e.pendingControlImages=e.pendingControlImages.filter(i=>i!==n)},controlNetModelChanged:(e,t)=>{const{controlNetId:n,model:r}=t.payload;if(e.controlNets[n].model=r,e.controlNets[n].processedControlImage=null,e.controlNets[n].shouldAutoConfig){let i;for(const o in _p)if(r.model_name.includes(o)){i=_p[o];break}i?(e.controlNets[n].processorType=i,e.controlNets[n].processorNode=Xl[i].default):(e.controlNets[n].processorType="none",e.controlNets[n].processorNode=Xl.none.default)}},controlNetWeightChanged:(e,t)=>{const{controlNetId:n,weight:r}=t.payload;e.controlNets[n].weight=r},controlNetBeginStepPctChanged:(e,t)=>{const{controlNetId:n,beginStepPct:r}=t.payload;e.controlNets[n].beginStepPct=r},controlNetEndStepPctChanged:(e,t)=>{const{controlNetId:n,endStepPct:r}=t.payload;e.controlNets[n].endStepPct=r},controlNetControlModeChanged:(e,t)=>{const{controlNetId:n,controlMode:r}=t.payload;e.controlNets[n].controlMode=r},controlNetResizeModeChanged:(e,t)=>{const{controlNetId:n,resizeMode:r}=t.payload;e.controlNets[n].resizeMode=r},controlNetProcessorParamsChanged:(e,t)=>{const{controlNetId:n,changes:r}=t.payload,i=e.controlNets[n].processorNode;e.controlNets[n].processorNode={...i,...r},e.controlNets[n].shouldAutoConfig=!1},controlNetProcessorTypeChanged:(e,t)=>{const{controlNetId:n,processorType:r}=t.payload;e.controlNets[n].processedControlImage=null,e.controlNets[n].processorType=r,e.controlNets[n].processorNode=Xl[r].default,e.controlNets[n].shouldAutoConfig=!1},controlNetAutoConfigToggled:(e,t)=>{var i;const{controlNetId:n}=t.payload,r=!e.controlNets[n].shouldAutoConfig;if(r){let o;for(const s in _p)if((i=e.controlNets[n].model)!=null&&i.model_name.includes(s)){o=_p[s];break}o?(e.controlNets[n].processorType=o,e.controlNets[n].processorNode=Xl[o].default):(e.controlNets[n].processorType="none",e.controlNets[n].processorNode=Xl.none.default)}e.controlNets[n].shouldAutoConfig=r},controlNetReset:()=>({...z_})},extraReducers:e=>{e.addCase(Gx,(t,n)=>{t.controlNets[n.payload.controlNetId].controlImage!==null&&t.pendingControlImages.push(n.payload.controlNetId)}),e.addCase(Ux,t=>{t.pendingControlImages=[]}),e.addMatcher(IR,t=>{t.pendingControlImages=[]}),e.addMatcher(he.endpoints.deleteImage.matchFulfilled,(t,n)=>{const{image_name:r}=n.meta.arg.originalArgs;Qa(t.controlNets,i=>{i.controlImage===r&&(i.controlImage=null,i.processedControlImage=null),i.processedControlImage===r&&(i.processedControlImage=null)})})}}),{isControlNetEnabledToggled:n3e,controlNetAdded:r3e,controlNetDuplicated:i3e,controlNetAddedFromImage:o3e,controlNetRemoved:C7,controlNetImageChanged:Hx,controlNetProcessedImageChanged:eJ,controlNetToggled:s3e,controlNetModelChanged:bT,controlNetWeightChanged:a3e,controlNetBeginStepPctChanged:l3e,controlNetEndStepPctChanged:u3e,controlNetControlModeChanged:c3e,controlNetResizeModeChanged:d3e,controlNetProcessorParamsChanged:tJ,controlNetProcessorTypeChanged:nJ,controlNetReset:T7,controlNetAutoConfigToggled:ST}=x7.actions,rJ=x7.reducer,E7={isEnabled:!1,maxPrompts:100,combinatorial:!0},iJ=E7,P7=Pt({name:"dynamicPrompts",initialState:iJ,reducers:{maxPromptsChanged:(e,t)=>{e.maxPrompts=t.payload},maxPromptsReset:e=>{e.maxPrompts=E7.maxPrompts},combinatorialToggled:e=>{e.combinatorial=!e.combinatorial},isEnabledToggled:e=>{e.isEnabled=!e.isEnabled}}}),{isEnabledToggled:f3e,maxPromptsChanged:h3e,maxPromptsReset:p3e,combinatorialToggled:g3e}=P7.actions,oJ=P7.reducer,sJ={updateBoardModalOpen:!1,searchText:""},A7=Pt({name:"boards",initialState:sJ,reducers:{setBoardSearchText:(e,t)=>{e.searchText=t.payload},setUpdateBoardModalOpen:(e,t)=>{e.updateBoardModalOpen=t.payload}}}),{setBoardSearchText:m3e,setUpdateBoardModalOpen:y3e}=A7.actions,aJ=A7.reducer,ec=Hs.injectEndpoints({endpoints:e=>({listBoards:e.query({query:t=>({url:"boards/",params:t}),providesTags:(t,n,r)=>{const i=[{type:"Board",id:Be}];return t&&i.push(...t.items.map(({board_id:o})=>({type:"Board",id:o}))),i}}),listAllBoards:e.query({query:()=>({url:"boards/",params:{all:!0}}),providesTags:(t,n,r)=>{const i=[{type:"Board",id:Be}];return t&&i.push(...t.map(({board_id:o})=>({type:"Board",id:o}))),i}}),listAllImageNamesForBoard:e.query({query:t=>({url:`boards/${t}/image_names`}),providesTags:(t,n,r)=>[{type:"ImageNameList",id:r}],keepUnusedDataFor:0}),createBoard:e.mutation({query:t=>({url:"boards/",method:"POST",params:{board_name:t}}),invalidatesTags:[{type:"Board",id:Be}]}),updateBoard:e.mutation({query:({board_id:t,changes:n})=>({url:`boards/${t}`,method:"PATCH",body:n}),invalidatesTags:(t,n,r)=>[{type:"Board",id:r.board_id}]}),deleteBoard:e.mutation({query:t=>({url:`boards/${t}`,method:"DELETE"}),invalidatesTags:(t,n,r)=>[{type:"Board",id:Be},{type:"ImageList",id:di({board_id:"none",categories:gi})},{type:"ImageList",id:di({board_id:"none",categories:_s})},{type:"BoardImagesTotal",id:"none"},{type:"BoardAssetsTotal",id:"none"}],async onQueryStarted(t,{dispatch:n,queryFulfilled:r,getState:i}){try{const{data:o}=await r,{deleted_board_images:s}=o;s.forEach(u=>{n(he.util.updateQueryData("getImageDTO",u,c=>{c.board_id=void 0}))});const a=[{categories:gi},{categories:_s}],l=s.map(u=>({id:u,changes:{board_id:void 0}}));a.forEach(u=>{n(he.util.updateQueryData("listImages",u,c=>{const d=c.total,h=Kn.updateMany(c,l).total-d;c.total=c.total+h}))})}catch{}}}),deleteBoardAndImages:e.mutation({query:t=>({url:`boards/${t}`,method:"DELETE",params:{include_images:!0}}),invalidatesTags:(t,n,r)=>[{type:"Board",id:Be},{type:"ImageList",id:di({board_id:"none",categories:gi})},{type:"ImageList",id:di({board_id:"none",categories:_s})},{type:"BoardImagesTotal",id:"none"},{type:"BoardAssetsTotal",id:"none"}],async onQueryStarted(t,{dispatch:n,queryFulfilled:r,getState:i}){try{const{data:o}=await r,{deleted_images:s}=o;[{categories:gi},{categories:_s}].forEach(l=>{n(he.util.updateQueryData("listImages",l,u=>{const c=u.total,f=Kn.removeMany(u,s).total-c;u.total=u.total+f}))})}catch{}}})})}),{useListBoardsQuery:v3e,useListAllBoardsQuery:b3e,useCreateBoardMutation:S3e,useUpdateBoardMutation:_3e,useDeleteBoardMutation:w3e,useDeleteBoardAndImagesMutation:x3e,useListAllImageNamesForBoardQuery:C3e}=ec,k7={selection:[],shouldAutoSwitch:!0,autoAddBoardId:void 0,galleryImageMinimumWidth:96,selectedBoardId:void 0,galleryView:"images",batchImageNames:[],isBatchEnabled:!1},O7=Pt({name:"gallery",initialState:k7,reducers:{imageRangeEndSelected:()=>{},imageSelectionToggled:()=>{},imageSelected:(e,t)=>{e.selection=t.payload?[t.payload]:[]},shouldAutoSwitchChanged:(e,t)=>{e.shouldAutoSwitch=t.payload},setGalleryImageMinimumWidth:(e,t)=>{e.galleryImageMinimumWidth=t.payload},boardIdSelected:(e,t)=>{e.selectedBoardId=t.payload,e.galleryView="images"},isBatchEnabledChanged:(e,t)=>{e.isBatchEnabled=t.payload},imagesAddedToBatch:(e,t)=>{e.batchImageNames=tY(e.batchImageNames.concat(t.payload))},imagesRemovedFromBatch:(e,t)=>{e.batchImageNames=e.batchImageNames.filter(r=>!t.payload.includes(r));const n=e.selection.filter(r=>!t.payload.includes(r));if(n.length){e.selection=n;return}e.selection=[e.batchImageNames[0]]},batchReset:e=>{e.batchImageNames=[],e.selection=[]},autoAddBoardIdChanged:(e,t)=>{e.autoAddBoardId=t.payload},galleryViewChanged:(e,t)=>{e.galleryView=t.payload}},extraReducers:e=>{e.addMatcher(uJ,(t,n)=>{const r=n.meta.arg.originalArgs;r===t.selectedBoardId&&(t.selectedBoardId=void 0,t.galleryView="images"),r===t.autoAddBoardId&&(t.autoAddBoardId=void 0)}),e.addMatcher(ec.endpoints.listAllBoards.matchFulfilled,(t,n)=>{const r=n.payload;t.autoAddBoardId&&(r.map(i=>i.board_id).includes(t.autoAddBoardId)||(t.autoAddBoardId=void 0))})}}),{imageRangeEndSelected:T3e,imageSelectionToggled:E3e,imageSelected:Rs,shouldAutoSwitchChanged:P3e,setGalleryImageMinimumWidth:A3e,boardIdSelected:U_,isBatchEnabledChanged:k3e,imagesAddedToBatch:G_,imagesRemovedFromBatch:O3e,autoAddBoardIdChanged:R3e,galleryViewChanged:Am}=O7.actions,lJ=O7.reducer,uJ=ei(ec.endpoints.deleteBoard.matchFulfilled,ec.endpoints.deleteBoardAndImages.matchFulfilled),cJ={imageToDelete:null,isModalOpen:!1},R7=Pt({name:"imageDeletion",initialState:cJ,reducers:{isModalOpenChanged:(e,t)=>{e.isModalOpen=t.payload},imageToDeleteSelected:(e,t)=>{e.imageToDelete=t.payload},imageToDeleteCleared:e=>{e.imageToDelete=null,e.isModalOpen=!1}}}),{isModalOpenChanged:I7,imageToDeleteSelected:dJ,imageToDeleteCleared:I3e}=R7.actions,fJ=R7.reducer,_T={weight:.75},hJ={loras:{}},M7=Pt({name:"lora",initialState:hJ,reducers:{loraAdded:(e,t)=>{const{model_name:n,id:r,base_model:i}=t.payload;e.loras[r]={id:r,model_name:n,base_model:i,..._T}},loraRemoved:(e,t)=>{const n=t.payload;delete e.loras[n]},lorasCleared:e=>{e.loras={}},loraWeightChanged:(e,t)=>{const{id:n,weight:r}=t.payload;e.loras[n].weight=r},loraWeightReset:(e,t)=>{const n=t.payload;e.loras[n].weight=_T.weight}}}),{loraAdded:M3e,loraRemoved:N7,loraWeightChanged:N3e,loraWeightReset:D3e,lorasCleared:L3e}=M7.actions,pJ=M7.reducer;function ti(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n{let t;const n=new Set,r=(l,u)=>{const c=typeof l=="function"?l(t):l;if(!Object.is(c,t)){const d=t;t=u??typeof c!="object"?c:Object.assign({},t,c),n.forEach(f=>f(t,d))}},i=()=>t,a={setState:r,getState:i,subscribe:l=>(n.add(l),()=>n.delete(l)),destroy:()=>{n.clear()}};return t=e(r,i,a),a},gJ=e=>e?wT(e):wT,{useSyncExternalStoreWithSelector:mJ}=Wj;function yJ(e,t=e.getState,n){const r=mJ(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return k.useDebugValue(r),r}function br(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,i]of e)if(!Object.is(i,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r=0;r{}};function P0(){for(var e=0,t=arguments.length,n={},r;e=0&&(r=n.slice(i+1),n=n.slice(0,i)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}hg.prototype=P0.prototype={constructor:hg,on:function(e,t){var n=this._,r=bJ(e+"",n),i,o=-1,s=r.length;if(arguments.length<2){for(;++o0)for(var n=new Array(i),r=0,i,o;r=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),CT.hasOwnProperty(t)?{space:CT[t],local:e}:e}function _J(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===H_&&t.documentElement.namespaceURI===H_?t.createElement(e):t.createElementNS(n,e)}}function wJ(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function D7(e){var t=A0(e);return(t.local?wJ:_J)(t)}function xJ(){}function qx(e){return e==null?xJ:function(){return this.querySelector(e)}}function CJ(e){typeof e!="function"&&(e=qx(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i=g&&(g=y+1);!(_=S[g])&&++g=0;)(s=r[i])&&(o&&s.compareDocumentPosition(o)^4&&o.parentNode.insertBefore(s,o),o=s);return this}function XJ(e){e||(e=YJ);function t(d,f){return d&&f?e(d.__data__,f.__data__):!d-!f}for(var n=this._groups,r=n.length,i=new Array(r),o=0;ot?1:e>=t?0:NaN}function QJ(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function ZJ(){return Array.from(this)}function JJ(){for(var e=this._groups,t=0,n=e.length;t1?this.each((t==null?cee:typeof t=="function"?fee:dee)(e,t,n??"")):tc(this.node(),e)}function tc(e,t){return e.style.getPropertyValue(t)||j7(e).getComputedStyle(e,null).getPropertyValue(t)}function pee(e){return function(){delete this[e]}}function gee(e,t){return function(){this[e]=t}}function mee(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function yee(e,t){return arguments.length>1?this.each((t==null?pee:typeof t=="function"?mee:gee)(e,t)):this.node()[e]}function V7(e){return e.trim().split(/^|\s+/)}function Wx(e){return e.classList||new z7(e)}function z7(e){this._node=e,this._names=V7(e.getAttribute("class")||"")}z7.prototype={add:function(e){var t=this._names.indexOf(e);t<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function U7(e,t){for(var n=Wx(e),r=-1,i=t.length;++r=0&&(n=t.slice(r+1),t=t.slice(0,r)),{type:t,name:n}})}function Hee(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,i=t.length,o;n()=>e;function q_(e,{sourceEvent:t,subject:n,target:r,identifier:i,active:o,x:s,y:a,dx:l,dy:u,dispatch:c}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:i,enumerable:!0,configurable:!0},active:{value:o,enumerable:!0,configurable:!0},x:{value:s,enumerable:!0,configurable:!0},y:{value:a,enumerable:!0,configurable:!0},dx:{value:l,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:c}})}q_.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function tte(e){return!e.ctrlKey&&!e.button}function nte(){return this.parentNode}function rte(e,t){return t??{x:e.x,y:e.y}}function ite(){return navigator.maxTouchPoints||"ontouchstart"in this}function ote(){var e=tte,t=nte,n=rte,r=ite,i={},o=P0("start","drag","end"),s=0,a,l,u,c,d=0;function f(b){b.on("mousedown.drag",h).filter(r).on("touchstart.drag",S).on("touchmove.drag",v,ete).on("touchend.drag touchcancel.drag",y).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(b,_){if(!(c||!e.call(this,b,_))){var w=g(this,t.call(this,b,_),b,_,"mouse");w&&(fi(b.view).on("mousemove.drag",p,Af).on("mouseup.drag",m,Af),W7(b.view),wb(b),u=!1,a=b.clientX,l=b.clientY,w("start",b))}}function p(b){if(Ou(b),!u){var _=b.clientX-a,w=b.clientY-l;u=_*_+w*w>d}i.mouse("drag",b)}function m(b){fi(b.view).on("mousemove.drag mouseup.drag",null),K7(b.view,u),Ou(b),i.mouse("end",b)}function S(b,_){if(e.call(this,b,_)){var w=b.changedTouches,x=t.call(this,b,_),T=w.length,P,E;for(P=0;P>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?xp(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?xp(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=ate.exec(e))?new hr(t[1],t[2],t[3],1):(t=lte.exec(e))?new hr(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=ute.exec(e))?xp(t[1],t[2],t[3],t[4]):(t=cte.exec(e))?xp(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=dte.exec(e))?RT(t[1],t[2]/100,t[3]/100,1):(t=fte.exec(e))?RT(t[1],t[2]/100,t[3]/100,t[4]):TT.hasOwnProperty(e)?AT(TT[e]):e==="transparent"?new hr(NaN,NaN,NaN,0):null}function AT(e){return new hr(e>>16&255,e>>8&255,e&255,1)}function xp(e,t,n,r){return r<=0&&(e=t=n=NaN),new hr(e,t,n,r)}function gte(e){return e instanceof bh||(e=Rf(e)),e?(e=e.rgb(),new hr(e.r,e.g,e.b,e.opacity)):new hr}function W_(e,t,n,r){return arguments.length===1?gte(e):new hr(e,t,n,r??1)}function hr(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}Kx(hr,W_,X7(bh,{brighter(e){return e=e==null?Om:Math.pow(Om,e),new hr(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?kf:Math.pow(kf,e),new hr(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new hr(Va(this.r),Va(this.g),Va(this.b),Rm(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:kT,formatHex:kT,formatHex8:mte,formatRgb:OT,toString:OT}));function kT(){return`#${Ma(this.r)}${Ma(this.g)}${Ma(this.b)}`}function mte(){return`#${Ma(this.r)}${Ma(this.g)}${Ma(this.b)}${Ma((isNaN(this.opacity)?1:this.opacity)*255)}`}function OT(){const e=Rm(this.opacity);return`${e===1?"rgb(":"rgba("}${Va(this.r)}, ${Va(this.g)}, ${Va(this.b)}${e===1?")":`, ${e})`}`}function Rm(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Va(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Ma(e){return e=Va(e),(e<16?"0":"")+e.toString(16)}function RT(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new hi(e,t,n,r)}function Y7(e){if(e instanceof hi)return new hi(e.h,e.s,e.l,e.opacity);if(e instanceof bh||(e=Rf(e)),!e)return new hi;if(e instanceof hi)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,i=Math.min(t,n,r),o=Math.max(t,n,r),s=NaN,a=o-i,l=(o+i)/2;return a?(t===o?s=(n-r)/a+(n0&&l<1?0:s,new hi(s,a,l,e.opacity)}function yte(e,t,n,r){return arguments.length===1?Y7(e):new hi(e,t,n,r??1)}function hi(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}Kx(hi,yte,X7(bh,{brighter(e){return e=e==null?Om:Math.pow(Om,e),new hi(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?kf:Math.pow(kf,e),new hi(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,i=2*n-r;return new hr(xb(e>=240?e-240:e+120,i,r),xb(e,i,r),xb(e<120?e+240:e-120,i,r),this.opacity)},clamp(){return new hi(IT(this.h),Cp(this.s),Cp(this.l),Rm(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=Rm(this.opacity);return`${e===1?"hsl(":"hsla("}${IT(this.h)}, ${Cp(this.s)*100}%, ${Cp(this.l)*100}%${e===1?")":`, ${e})`}`}}));function IT(e){return e=(e||0)%360,e<0?e+360:e}function Cp(e){return Math.max(0,Math.min(1,e||0))}function xb(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const Q7=e=>()=>e;function vte(e,t){return function(n){return e+n*t}}function bte(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function Ste(e){return(e=+e)==1?Z7:function(t,n){return n-t?bte(t,n,e):Q7(isNaN(t)?n:t)}}function Z7(e,t){var n=t-e;return n?vte(e,n):Q7(isNaN(e)?t:e)}const MT=function e(t){var n=Ste(t);function r(i,o){var s=n((i=W_(i)).r,(o=W_(o)).r),a=n(i.g,o.g),l=n(i.b,o.b),u=Z7(i.opacity,o.opacity);return function(c){return i.r=s(c),i.g=a(c),i.b=l(c),i.opacity=u(c),i+""}}return r.gamma=e,r}(1);function cs(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}var K_=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Cb=new RegExp(K_.source,"g");function _te(e){return function(){return e}}function wte(e){return function(t){return e(t)+""}}function xte(e,t){var n=K_.lastIndex=Cb.lastIndex=0,r,i,o,s=-1,a=[],l=[];for(e=e+"",t=t+"";(r=K_.exec(e))&&(i=Cb.exec(t));)(o=i.index)>n&&(o=t.slice(n,o),a[s]?a[s]+=o:a[++s]=o),(r=r[0])===(i=i[0])?a[s]?a[s]+=i:a[++s]=i:(a[++s]=null,l.push({i:s,x:cs(r,i)})),n=Cb.lastIndex;return n180?c+=360:c-u>180&&(u+=360),f.push({i:d.push(i(d)+"rotate(",null,r)-2,x:cs(u,c)})):c&&d.push(i(d)+"rotate("+c+r)}function a(u,c,d,f){u!==c?f.push({i:d.push(i(d)+"skewX(",null,r)-2,x:cs(u,c)}):c&&d.push(i(d)+"skewX("+c+r)}function l(u,c,d,f,h,p){if(u!==d||c!==f){var m=h.push(i(h)+"scale(",null,",",null,")");p.push({i:m-4,x:cs(u,d)},{i:m-2,x:cs(c,f)})}else(d!==1||f!==1)&&h.push(i(h)+"scale("+d+","+f+")")}return function(u,c){var d=[],f=[];return u=e(u),c=e(c),o(u.translateX,u.translateY,c.translateX,c.translateY,d,f),s(u.rotate,c.rotate,d,f),a(u.skewX,c.skewX,d,f),l(u.scaleX,u.scaleY,c.scaleX,c.scaleY,d,f),u=c=null,function(h){for(var p=-1,m=f.length,S;++p=0&&e._call.call(void 0,t),e=e._next;--nc}function LT(){tl=(Mm=If.now())+k0,nc=fd=0;try{Mte()}finally{nc=0,Dte(),tl=0}}function Nte(){var e=If.now(),t=e-Mm;t>tI&&(k0-=t,Mm=e)}function Dte(){for(var e,t=Im,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:Im=n);hd=e,Y_(r)}function Y_(e){if(!nc){fd&&(fd=clearTimeout(fd));var t=e-tl;t>24?(e<1/0&&(fd=setTimeout(LT,e-If.now()-k0)),Gc&&(Gc=clearInterval(Gc))):(Gc||(Mm=If.now(),Gc=setInterval(Nte,tI)),nc=1,nI(LT))}}function $T(e,t,n){var r=new Nm;return t=t==null?0:+t,r.restart(i=>{r.stop(),e(i+t)},t,n),r}var Lte=P0("start","end","cancel","interrupt"),$te=[],iI=0,FT=1,Q_=2,pg=3,BT=4,Z_=5,gg=6;function O0(e,t,n,r,i,o){var s=e.__transition;if(!s)e.__transition={};else if(n in s)return;Fte(e,n,{name:t,index:r,group:i,on:Lte,tween:$te,time:o.time,delay:o.delay,duration:o.duration,ease:o.ease,timer:null,state:iI})}function Yx(e,t){var n=Pi(e,t);if(n.state>iI)throw new Error("too late; already scheduled");return n}function so(e,t){var n=Pi(e,t);if(n.state>pg)throw new Error("too late; already running");return n}function Pi(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function Fte(e,t,n){var r=e.__transition,i;r[t]=n,n.timer=rI(o,0,n.time);function o(u){n.state=FT,n.timer.restart(s,n.delay,n.time),n.delay<=u&&s(u-n.delay)}function s(u){var c,d,f,h;if(n.state!==FT)return l();for(c in r)if(h=r[c],h.name===n.name){if(h.state===pg)return $T(s);h.state===BT?(h.state=gg,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[c]):+cQ_&&r.state=0&&(t=t.slice(0,n)),!t||t==="start"})}function pne(e,t,n){var r,i,o=hne(t)?Yx:so;return function(){var s=o(this,e),a=s.on;a!==r&&(i=(r=a).copy()).on(t,n),s.on=i}}function gne(e,t){var n=this._id;return arguments.length<2?Pi(this.node(),n).on.on(e):this.each(pne(n,e,t))}function mne(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function yne(){return this.on("end.remove",mne(this._id))}function vne(e){var t=this._name,n=this._id;typeof e!="function"&&(e=qx(e));for(var r=this._groups,i=r.length,o=new Array(i),s=0;s()=>e;function Une(e,{sourceEvent:t,target:n,transform:r,dispatch:i}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:i}})}function Po(e,t,n){this.k=e,this.x=t,this.y=n}Po.prototype={constructor:Po,scale:function(e){return e===1?this:new Po(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Po(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var Is=new Po(1,0,0);Po.prototype;function Tb(e){e.stopImmediatePropagation()}function Hc(e){e.preventDefault(),e.stopImmediatePropagation()}function Gne(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function Hne(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute("viewBox")?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function jT(){return this.__zoom||Is}function qne(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function Wne(){return navigator.maxTouchPoints||"ontouchstart"in this}function Kne(e,t,n){var r=e.invertX(t[0][0])-n[0][0],i=e.invertX(t[1][0])-n[1][0],o=e.invertY(t[0][1])-n[0][1],s=e.invertY(t[1][1])-n[1][1];return e.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),s>o?(o+s)/2:Math.min(0,o)||Math.max(0,s))}function Xne(){var e=Gne,t=Hne,n=Kne,r=qne,i=Wne,o=[0,1/0],s=[[-1/0,-1/0],[1/0,1/0]],a=250,l=Rte,u=P0("start","zoom","end"),c,d,f,h=500,p=150,m=0,S=10;function v(C){C.property("__zoom",jT).on("wheel.zoom",T,{passive:!1}).on("mousedown.zoom",P).on("dblclick.zoom",E).filter(i).on("touchstart.zoom",A).on("touchmove.zoom",$).on("touchend.zoom touchcancel.zoom",M).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}v.transform=function(C,O,I,N){var R=C.selection?C.selection():C;R.property("__zoom",jT),C!==R?_(C,O,I,N):R.interrupt().each(function(){w(this,arguments).event(N).start().zoom(null,typeof O=="function"?O.apply(this,arguments):O).end()})},v.scaleBy=function(C,O,I,N){v.scaleTo(C,function(){var R=this.__zoom.k,D=typeof O=="function"?O.apply(this,arguments):O;return R*D},I,N)},v.scaleTo=function(C,O,I,N){v.transform(C,function(){var R=t.apply(this,arguments),D=this.__zoom,L=I==null?b(R):typeof I=="function"?I.apply(this,arguments):I,j=D.invert(L),U=typeof O=="function"?O.apply(this,arguments):O;return n(g(y(D,U),L,j),R,s)},I,N)},v.translateBy=function(C,O,I,N){v.transform(C,function(){return n(this.__zoom.translate(typeof O=="function"?O.apply(this,arguments):O,typeof I=="function"?I.apply(this,arguments):I),t.apply(this,arguments),s)},null,N)},v.translateTo=function(C,O,I,N,R){v.transform(C,function(){var D=t.apply(this,arguments),L=this.__zoom,j=N==null?b(D):typeof N=="function"?N.apply(this,arguments):N;return n(Is.translate(j[0],j[1]).scale(L.k).translate(typeof O=="function"?-O.apply(this,arguments):-O,typeof I=="function"?-I.apply(this,arguments):-I),D,s)},N,R)};function y(C,O){return O=Math.max(o[0],Math.min(o[1],O)),O===C.k?C:new Po(O,C.x,C.y)}function g(C,O,I){var N=O[0]-I[0]*C.k,R=O[1]-I[1]*C.k;return N===C.x&&R===C.y?C:new Po(C.k,N,R)}function b(C){return[(+C[0][0]+ +C[1][0])/2,(+C[0][1]+ +C[1][1])/2]}function _(C,O,I,N){C.on("start.zoom",function(){w(this,arguments).event(N).start()}).on("interrupt.zoom end.zoom",function(){w(this,arguments).event(N).end()}).tween("zoom",function(){var R=this,D=arguments,L=w(R,D).event(N),j=t.apply(R,D),U=I==null?b(j):typeof I=="function"?I.apply(R,D):I,G=Math.max(j[1][0]-j[0][0],j[1][1]-j[0][1]),W=R.__zoom,X=typeof O=="function"?O.apply(R,D):O,Y=l(W.invert(U).concat(G/W.k),X.invert(U).concat(G/X.k));return function(B){if(B===1)B=X;else{var H=Y(B),Q=G/H[2];B=new Po(Q,U[0]-H[0]*Q,U[1]-H[1]*Q)}L.zoom(null,B)}})}function w(C,O,I){return!I&&C.__zooming||new x(C,O)}function x(C,O){this.that=C,this.args=O,this.active=0,this.sourceEvent=null,this.extent=t.apply(C,O),this.taps=0}x.prototype={event:function(C){return C&&(this.sourceEvent=C),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(C,O){return this.mouse&&C!=="mouse"&&(this.mouse[1]=O.invert(this.mouse[0])),this.touch0&&C!=="touch"&&(this.touch0[1]=O.invert(this.touch0[0])),this.touch1&&C!=="touch"&&(this.touch1[1]=O.invert(this.touch1[0])),this.that.__zoom=O,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(C){var O=fi(this.that).datum();u.call(C,this.that,new Une(C,{sourceEvent:this.sourceEvent,target:v,type:C,transform:this.that.__zoom,dispatch:u}),O)}};function T(C,...O){if(!e.apply(this,arguments))return;var I=w(this,O).event(C),N=this.__zoom,R=Math.max(o[0],Math.min(o[1],N.k*Math.pow(2,r.apply(this,arguments)))),D=$i(C);if(I.wheel)(I.mouse[0][0]!==D[0]||I.mouse[0][1]!==D[1])&&(I.mouse[1]=N.invert(I.mouse[0]=D)),clearTimeout(I.wheel);else{if(N.k===R)return;I.mouse=[D,N.invert(D)],mg(this),I.start()}Hc(C),I.wheel=setTimeout(L,p),I.zoom("mouse",n(g(y(N,R),I.mouse[0],I.mouse[1]),I.extent,s));function L(){I.wheel=null,I.end()}}function P(C,...O){if(f||!e.apply(this,arguments))return;var I=C.currentTarget,N=w(this,O,!0).event(C),R=fi(C.view).on("mousemove.zoom",U,!0).on("mouseup.zoom",G,!0),D=$i(C,I),L=C.clientX,j=C.clientY;W7(C.view),Tb(C),N.mouse=[D,this.__zoom.invert(D)],mg(this),N.start();function U(W){if(Hc(W),!N.moved){var X=W.clientX-L,Y=W.clientY-j;N.moved=X*X+Y*Y>m}N.event(W).zoom("mouse",n(g(N.that.__zoom,N.mouse[0]=$i(W,I),N.mouse[1]),N.extent,s))}function G(W){R.on("mousemove.zoom mouseup.zoom",null),K7(W.view,N.moved),Hc(W),N.event(W).end()}}function E(C,...O){if(e.apply(this,arguments)){var I=this.__zoom,N=$i(C.changedTouches?C.changedTouches[0]:C,this),R=I.invert(N),D=I.k*(C.shiftKey?.5:2),L=n(g(y(I,D),N,R),t.apply(this,O),s);Hc(C),a>0?fi(this).transition().duration(a).call(_,L,N,C):fi(this).call(v.transform,L,N,C)}}function A(C,...O){if(e.apply(this,arguments)){var I=C.touches,N=I.length,R=w(this,O,C.changedTouches.length===N).event(C),D,L,j,U;for(Tb(C),L=0;L"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,t)=>`Couldn't create edge for ${e?"target":"source"} handle id: "${e?t.targetHandle:t.sourceHandle}", edge id: ${t.id}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`},lI=qs.error001();function Vt(e,t){const n=k.useContext(R0);if(n===null)throw new Error(lI);return yJ(n,e,t)}const Vn=()=>{const e=k.useContext(R0);if(e===null)throw new Error(lI);return k.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe,destroy:e.destroy}),[e])},Qne=e=>e.userSelectionActive?"none":"all";function Zne({position:e,children:t,className:n,style:r,...i}){const o=Vt(Qne),s=`${e}`.split("-");return K.jsx("div",{className:ti(["react-flow__panel",n,...s]),style:{...r,pointerEvents:o},...i,children:t})}function Jne({proOptions:e,position:t="bottom-right"}){return e!=null&&e.hideAttribution?null:K.jsx(Zne,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:K.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const ere=({x:e,y:t,label:n,labelStyle:r={},labelShowBg:i=!0,labelBgStyle:o={},labelBgPadding:s=[2,4],labelBgBorderRadius:a=2,children:l,className:u,...c})=>{const d=k.useRef(null),[f,h]=k.useState({x:0,y:0,width:0,height:0}),p=ti(["react-flow__edge-textwrapper",u]);return k.useEffect(()=>{if(d.current){const m=d.current.getBBox();h({x:m.x,y:m.y,width:m.width,height:m.height})}},[n]),typeof n>"u"||!n?null:K.jsxs("g",{transform:`translate(${e-f.width/2} ${t-f.height/2})`,className:p,visibility:f.width?"visible":"hidden",...c,children:[i&&K.jsx("rect",{width:f.width+2*s[0],x:-s[0],y:-s[1],height:f.height+2*s[1],className:"react-flow__edge-textbg",style:o,rx:a,ry:a}),K.jsx("text",{className:"react-flow__edge-text",y:f.height/2,dy:"0.3em",ref:d,style:r,children:n}),l]})};var tre=k.memo(ere);const Zx=e=>({width:e.offsetWidth,height:e.offsetHeight}),rc=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Jx=(e={x:0,y:0},t)=>({x:rc(e.x,t[0][0],t[1][0]),y:rc(e.y,t[0][1],t[1][1])}),VT=(e,t,n)=>en?-rc(Math.abs(e-n),1,50)/50:0,uI=(e,t)=>{const n=VT(e.x,35,t.width-35)*20,r=VT(e.y,35,t.height-35)*20;return[n,r]},cI=e=>{var t;return((t=e.getRootNode)==null?void 0:t.call(e))||(window==null?void 0:window.document)},dI=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Dm=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),fI=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),zT=e=>({...e.positionAbsolute||{x:0,y:0},width:e.width||0,height:e.height||0}),$3e=(e,t)=>fI(dI(Dm(e),Dm(t))),J_=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},nre=e=>Kr(e.width)&&Kr(e.height)&&Kr(e.x)&&Kr(e.y),Kr=e=>!isNaN(e)&&isFinite(e),on=Symbol.for("internals"),hI=["Enter"," ","Escape"],rre=(e,t)=>{},ire=e=>"nativeEvent"in e;function e2(e){var i,o;const t=ire(e)?e.nativeEvent:e,n=((o=(i=t.composedPath)==null?void 0:i.call(t))==null?void 0:o[0])||e.target;return["INPUT","SELECT","TEXTAREA"].includes(n==null?void 0:n.nodeName)||(n==null?void 0:n.hasAttribute("contenteditable"))||!!(n!=null&&n.closest(".nokey"))}const pI=e=>"clientX"in e,Ms=(e,t)=>{var o,s;const n=pI(e),r=n?e.clientX:(o=e.touches)==null?void 0:o[0].clientX,i=n?e.clientY:(s=e.touches)==null?void 0:s[0].clientY;return{x:r-((t==null?void 0:t.left)??0),y:i-((t==null?void 0:t.top)??0)}},Sh=({id:e,path:t,labelX:n,labelY:r,label:i,labelStyle:o,labelShowBg:s,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:u,style:c,markerEnd:d,markerStart:f,interactionWidth:h=20})=>K.jsxs(K.Fragment,{children:[K.jsx("path",{id:e,style:c,d:t,fill:"none",className:"react-flow__edge-path",markerEnd:d,markerStart:f}),h&&K.jsx("path",{d:t,fill:"none",strokeOpacity:0,strokeWidth:h,className:"react-flow__edge-interaction"}),i&&Kr(n)&&Kr(r)?K.jsx(tre,{x:n,y:r,label:i,labelStyle:o,labelShowBg:s,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:u}):null]});Sh.displayName="BaseEdge";function qc(e,t,n){return n===void 0?n:r=>{const i=t().edges.find(o=>o.id===e);i&&n(r,{...i})}}function gI({sourceX:e,sourceY:t,targetX:n,targetY:r}){const i=Math.abs(n-e)/2,o=n{const[S,v,y]=yI({sourceX:e,sourceY:t,sourcePosition:i,targetX:n,targetY:r,targetPosition:o});return K.jsx(Sh,{path:S,labelX:v,labelY:y,label:s,labelStyle:a,labelShowBg:l,labelBgStyle:u,labelBgPadding:c,labelBgBorderRadius:d,style:f,markerEnd:h,markerStart:p,interactionWidth:m})});eC.displayName="SimpleBezierEdge";const GT={[pe.Left]:{x:-1,y:0},[pe.Right]:{x:1,y:0},[pe.Top]:{x:0,y:-1},[pe.Bottom]:{x:0,y:1}},ore=({source:e,sourcePosition:t=pe.Bottom,target:n})=>t===pe.Left||t===pe.Right?e.xMath.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function sre({source:e,sourcePosition:t=pe.Bottom,target:n,targetPosition:r=pe.Top,center:i,offset:o}){const s=GT[t],a=GT[r],l={x:e.x+s.x*o,y:e.y+s.y*o},u={x:n.x+a.x*o,y:n.y+a.y*o},c=ore({source:l,sourcePosition:t,target:u}),d=c.x!==0?"x":"y",f=c[d];let h=[],p,m;const[S,v,y,g]=gI({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(s[d]*a[d]===-1){p=i.x||S,m=i.y||v;const _=[{x:p,y:l.y},{x:p,y:u.y}],w=[{x:l.x,y:m},{x:u.x,y:m}];s[d]===f?h=d==="x"?_:w:h=d==="x"?w:_}else{const _=[{x:l.x,y:u.y}],w=[{x:u.x,y:l.y}];if(d==="x"?h=s.x===f?w:_:h=s.y===f?_:w,t!==r){const x=d==="x"?"y":"x",T=s[d]===a[x],P=l[x]>u[x],E=l[x]{let g="";return y>0&&y{const[v,y,g]=t2({sourceX:e,sourceY:t,sourcePosition:d,targetX:n,targetY:r,targetPosition:f,borderRadius:m==null?void 0:m.borderRadius,offset:m==null?void 0:m.offset});return K.jsx(Sh,{path:v,labelX:y,labelY:g,label:i,labelStyle:o,labelShowBg:s,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:u,style:c,markerEnd:h,markerStart:p,interactionWidth:S})});I0.displayName="SmoothStepEdge";const tC=k.memo(e=>{var t;return K.jsx(I0,{...e,pathOptions:k.useMemo(()=>{var n;return{borderRadius:0,offset:(n=e.pathOptions)==null?void 0:n.offset}},[(t=e.pathOptions)==null?void 0:t.offset])})});tC.displayName="StepEdge";function lre({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[i,o,s,a]=gI({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,i,o,s,a]}const nC=k.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,label:i,labelStyle:o,labelShowBg:s,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:u,style:c,markerEnd:d,markerStart:f,interactionWidth:h})=>{const[p,m,S]=lre({sourceX:e,sourceY:t,targetX:n,targetY:r});return K.jsx(Sh,{path:p,labelX:m,labelY:S,label:i,labelStyle:o,labelShowBg:s,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:u,style:c,markerEnd:d,markerStart:f,interactionWidth:h})});nC.displayName="StraightEdge";function Pp(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function qT({pos:e,x1:t,y1:n,x2:r,y2:i,c:o}){switch(e){case pe.Left:return[t-Pp(t-r,o),n];case pe.Right:return[t+Pp(r-t,o),n];case pe.Top:return[t,n-Pp(n-i,o)];case pe.Bottom:return[t,n+Pp(i-n,o)]}}function vI({sourceX:e,sourceY:t,sourcePosition:n=pe.Bottom,targetX:r,targetY:i,targetPosition:o=pe.Top,curvature:s=.25}){const[a,l]=qT({pos:n,x1:e,y1:t,x2:r,y2:i,c:s}),[u,c]=qT({pos:o,x1:r,y1:i,x2:e,y2:t,c:s}),[d,f,h,p]=mI({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:a,sourceControlY:l,targetControlX:u,targetControlY:c});return[`M${e},${t} C${a},${l} ${u},${c} ${r},${i}`,d,f,h,p]}const $m=k.memo(({sourceX:e,sourceY:t,targetX:n,targetY:r,sourcePosition:i=pe.Bottom,targetPosition:o=pe.Top,label:s,labelStyle:a,labelShowBg:l,labelBgStyle:u,labelBgPadding:c,labelBgBorderRadius:d,style:f,markerEnd:h,markerStart:p,pathOptions:m,interactionWidth:S})=>{const[v,y,g]=vI({sourceX:e,sourceY:t,sourcePosition:i,targetX:n,targetY:r,targetPosition:o,curvature:m==null?void 0:m.curvature});return K.jsx(Sh,{path:v,labelX:y,labelY:g,label:s,labelStyle:a,labelShowBg:l,labelBgStyle:u,labelBgPadding:c,labelBgBorderRadius:d,style:f,markerEnd:h,markerStart:p,interactionWidth:S})});$m.displayName="BezierEdge";const rC=k.createContext(null),ure=rC.Provider;rC.Consumer;const cre=()=>k.useContext(rC),dre=e=>"id"in e&&"source"in e&&"target"in e,fre=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`reactflow__edge-${e}${t||""}-${n}${r||""}`,n2=(e,t)=>typeof e>"u"?"":typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`,hre=(e,t)=>t.some(n=>n.source===e.source&&n.target===e.target&&(n.sourceHandle===e.sourceHandle||!n.sourceHandle&&!e.sourceHandle)&&(n.targetHandle===e.targetHandle||!n.targetHandle&&!e.targetHandle)),bI=(e,t)=>{if(!e.source||!e.target)return t;let n;return dre(e)?n={...e}:n={...e,id:fre(e)},hre(n,t)?t:t.concat(n)},SI=({x:e,y:t},[n,r,i],o,[s,a])=>{const l={x:(e-n)/i,y:(t-r)/i};return o?{x:s*Math.round(l.x/s),y:a*Math.round(l.y/a)}:l},pre=({x:e,y:t},[n,r,i])=>({x:e*i+n,y:t*i+r}),Mu=(e,t=[0,0])=>{if(!e)return{x:0,y:0,positionAbsolute:{x:0,y:0}};const n=(e.width??0)*t[0],r=(e.height??0)*t[1],i={x:e.position.x-n,y:e.position.y-r};return{...i,positionAbsolute:e.positionAbsolute?{x:e.positionAbsolute.x-n,y:e.positionAbsolute.y-r}:i}},_I=(e,t=[0,0])=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,i)=>{const{x:o,y:s}=Mu(i,t).positionAbsolute;return dI(r,Dm({x:o,y:s,width:i.width||0,height:i.height||0}))},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return fI(n)},wI=(e,t,[n,r,i]=[0,0,1],o=!1,s=!1,a=[0,0])=>{const l={x:(t.x-n)/i,y:(t.y-r)/i,width:t.width/i,height:t.height/i},u=[];return e.forEach(c=>{const{width:d,height:f,selectable:h=!0,hidden:p=!1}=c;if(s&&!h||p)return!1;const{positionAbsolute:m}=Mu(c,a),S={x:m.x,y:m.y,width:d||0,height:f||0},v=J_(l,S),y=typeof d>"u"||typeof f>"u"||d===null||f===null,g=o&&v>0,b=(d||0)*(f||0);(y||g||v>=b||c.dragging)&&u.push(c)}),u},xI=(e,t)=>{const n=e.map(r=>r.id);return t.filter(r=>n.includes(r.source)||n.includes(r.target))},CI=(e,t,n,r,i,o=.1)=>{const s=t/(e.width*(1+o)),a=n/(e.height*(1+o)),l=Math.min(s,a),u=rc(l,r,i),c=e.x+e.width/2,d=e.y+e.height/2,f=t/2-c*u,h=n/2-d*u;return[f,h,u]},xa=(e,t=0)=>e.transition().duration(t);function WT(e,t,n,r){return(t[n]||[]).reduce((i,o)=>{var s,a;return`${e.id}-${o.id}-${n}`!==r&&i.push({id:o.id||null,type:n,nodeId:e.id,x:(((s=e.positionAbsolute)==null?void 0:s.x)??0)+o.x+o.width/2,y:(((a=e.positionAbsolute)==null?void 0:a.y)??0)+o.y+o.height/2}),i},[])}function gre(e,t,n,r,i,o){const{x:s,y:a}=Ms(e),u=t.elementsFromPoint(s,a).find(p=>p.classList.contains("react-flow__handle"));if(u){const p=u.getAttribute("data-nodeid");if(p){const m=iC(void 0,u),S=u.getAttribute("data-handleid"),v=o({nodeId:p,id:S,type:m});if(v)return{handle:{id:S,type:m,nodeId:p,x:n.x,y:n.y},validHandleResult:v}}}let c=[],d=1/0;if(i.forEach(p=>{const m=Math.sqrt((p.x-n.x)**2+(p.y-n.y)**2);if(m<=r){const S=o(p);m<=d&&(mp.isValid),h=c.some(({handle:p})=>p.type==="target");return c.find(({handle:p,validHandleResult:m})=>h?p.type==="target":f?m.isValid:!0)||c[0]}const mre={source:null,target:null,sourceHandle:null,targetHandle:null},TI=()=>({handleDomNode:null,isValid:!1,connection:mre,endHandle:null});function EI(e,t,n,r,i,o,s){const a=i==="target",l=s.querySelector(`.react-flow__handle[data-id="${e==null?void 0:e.nodeId}-${e==null?void 0:e.id}-${e==null?void 0:e.type}"]`),u={...TI(),handleDomNode:l};if(l){const c=iC(void 0,l),d=l.getAttribute("data-nodeid"),f=l.getAttribute("data-handleid"),h=l.classList.contains("connectable"),p=l.classList.contains("connectableend"),m={source:a?d:n,sourceHandle:a?f:r,target:a?n:d,targetHandle:a?r:f};u.connection=m,h&&p&&(t===nl.Strict?a&&c==="source"||!a&&c==="target":d!==n||f!==r)&&(u.endHandle={nodeId:d,handleId:f,type:c},u.isValid=o(m))}return u}function yre({nodes:e,nodeId:t,handleId:n,handleType:r}){return e.reduce((i,o)=>{if(o[on]){const{handleBounds:s}=o[on];let a=[],l=[];s&&(a=WT(o,s,"source",`${t}-${n}-${r}`),l=WT(o,s,"target",`${t}-${n}-${r}`)),i.push(...a,...l)}return i},[])}function iC(e,t){return e||(t!=null&&t.classList.contains("target")?"target":t!=null&&t.classList.contains("source")?"source":null)}function Eb(e){e==null||e.classList.remove("valid","connecting","react-flow__handle-valid","react-flow__handle-connecting")}function vre(e,t){let n=null;return t?n="valid":e&&!t&&(n="invalid"),n}function PI({event:e,handleId:t,nodeId:n,onConnect:r,isTarget:i,getState:o,setState:s,isValidConnection:a,edgeUpdaterType:l,onEdgeUpdateEnd:u}){const c=cI(e.target),{connectionMode:d,domNode:f,autoPanOnConnect:h,connectionRadius:p,onConnectStart:m,panBy:S,getNodes:v,cancelConnection:y}=o();let g=0,b;const{x:_,y:w}=Ms(e),x=c==null?void 0:c.elementFromPoint(_,w),T=iC(l,x),P=f==null?void 0:f.getBoundingClientRect();if(!P||!T)return;let E,A=Ms(e,P),$=!1,M=null,C=!1,O=null;const I=yre({nodes:v(),nodeId:n,handleId:t,handleType:T}),N=()=>{if(!h)return;const[L,j]=uI(A,P);S({x:L,y:j}),g=requestAnimationFrame(N)};s({connectionPosition:A,connectionStatus:null,connectionNodeId:n,connectionHandleId:t,connectionHandleType:T,connectionStartHandle:{nodeId:n,handleId:t,type:T},connectionEndHandle:null}),m==null||m(e,{nodeId:n,handleId:t,handleType:T});function R(L){const{transform:j}=o();A=Ms(L,P);const{handle:U,validHandleResult:G}=gre(L,c,SI(A,j,!1,[1,1]),p,I,W=>EI(W,d,n,t,i?"target":"source",a,c));if(b=U,$||(N(),$=!0),O=G.handleDomNode,M=G.connection,C=G.isValid,s({connectionPosition:b&&C?pre({x:b.x,y:b.y},j):A,connectionStatus:vre(!!b,C),connectionEndHandle:G.endHandle}),!b&&!C&&!O)return Eb(E);M.source!==M.target&&O&&(Eb(E),E=O,O.classList.add("connecting","react-flow__handle-connecting"),O.classList.toggle("valid",C),O.classList.toggle("react-flow__handle-valid",C))}function D(L){var j,U;(b||O)&&M&&C&&(r==null||r(M)),(U=(j=o()).onConnectEnd)==null||U.call(j,L),l&&(u==null||u(L)),Eb(E),y(),cancelAnimationFrame(g),$=!1,C=!1,M=null,O=null,c.removeEventListener("mousemove",R),c.removeEventListener("mouseup",D),c.removeEventListener("touchmove",R),c.removeEventListener("touchend",D)}c.addEventListener("mousemove",R),c.addEventListener("mouseup",D),c.addEventListener("touchmove",R),c.addEventListener("touchend",D)}const KT=()=>!0,bre=e=>({connectionStartHandle:e.connectionStartHandle,connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName}),Sre=(e,t,n)=>r=>{const{connectionStartHandle:i,connectionEndHandle:o,connectionClickStartHandle:s}=r;return{connecting:(i==null?void 0:i.nodeId)===e&&(i==null?void 0:i.handleId)===t&&(i==null?void 0:i.type)===n||(o==null?void 0:o.nodeId)===e&&(o==null?void 0:o.handleId)===t&&(o==null?void 0:o.type)===n,clickConnecting:(s==null?void 0:s.nodeId)===e&&(s==null?void 0:s.handleId)===t&&(s==null?void 0:s.type)===n}},AI=k.forwardRef(({type:e="source",position:t=pe.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:i=!0,isConnectableEnd:o=!0,id:s,onConnect:a,children:l,className:u,onMouseDown:c,onTouchStart:d,...f},h)=>{var P,E;const p=s||null,m=e==="target",S=Vn(),v=cre(),{connectOnClick:y,noPanClassName:g}=Vt(bre,br),{connecting:b,clickConnecting:_}=Vt(Sre(v,p,e),br);v||(E=(P=S.getState()).onError)==null||E.call(P,"010",qs.error010());const w=A=>{const{defaultEdgeOptions:$,onConnect:M,hasDefaultEdges:C}=S.getState(),O={...$,...A};if(C){const{edges:I,setEdges:N}=S.getState();N(bI(O,I))}M==null||M(O),a==null||a(O)},x=A=>{if(!v)return;const $=pI(A);i&&($&&A.button===0||!$)&&PI({event:A,handleId:p,nodeId:v,onConnect:w,isTarget:m,getState:S.getState,setState:S.setState,isValidConnection:n||S.getState().isValidConnection||KT}),$?c==null||c(A):d==null||d(A)},T=A=>{const{onClickConnectStart:$,onClickConnectEnd:M,connectionClickStartHandle:C,connectionMode:O,isValidConnection:I}=S.getState();if(!v||!C&&!i)return;if(!C){$==null||$(A,{nodeId:v,handleId:p,handleType:e}),S.setState({connectionClickStartHandle:{nodeId:v,type:e,handleId:p}});return}const N=cI(A.target),R=n||I||KT,{connection:D,isValid:L}=EI({nodeId:v,id:p,type:e},O,C.nodeId,C.handleId||null,C.type,R,N);L&&w(D),M==null||M(A),S.setState({connectionClickStartHandle:null})};return K.jsx("div",{"data-handleid":p,"data-nodeid":v,"data-handlepos":t,"data-id":`${v}-${p}-${e}`,className:ti(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",g,u,{source:!m,target:m,connectable:r,connectablestart:i,connectableend:o,connecting:_,connectionindicator:r&&(i&&!b||o&&b)}]),onMouseDown:x,onTouchStart:x,onClick:y?T:void 0,ref:h,...f,children:l})});AI.displayName="Handle";var Fm=k.memo(AI);const kI=({data:e,isConnectable:t,targetPosition:n=pe.Top,sourcePosition:r=pe.Bottom})=>K.jsxs(K.Fragment,{children:[K.jsx(Fm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label,K.jsx(Fm,{type:"source",position:r,isConnectable:t})]});kI.displayName="DefaultNode";var r2=k.memo(kI);const OI=({data:e,isConnectable:t,sourcePosition:n=pe.Bottom})=>K.jsxs(K.Fragment,{children:[e==null?void 0:e.label,K.jsx(Fm,{type:"source",position:n,isConnectable:t})]});OI.displayName="InputNode";var RI=k.memo(OI);const II=({data:e,isConnectable:t,targetPosition:n=pe.Top})=>K.jsxs(K.Fragment,{children:[K.jsx(Fm,{type:"target",position:n,isConnectable:t}),e==null?void 0:e.label]});II.displayName="OutputNode";var MI=k.memo(II);const oC=()=>null;oC.displayName="GroupNode";const _re=e=>({selectedNodes:e.getNodes().filter(t=>t.selected),selectedEdges:e.edges.filter(t=>t.selected)}),Ap=e=>e.id;function wre(e,t){return br(e.selectedNodes.map(Ap),t.selectedNodes.map(Ap))&&br(e.selectedEdges.map(Ap),t.selectedEdges.map(Ap))}const NI=k.memo(({onSelectionChange:e})=>{const t=Vn(),{selectedNodes:n,selectedEdges:r}=Vt(_re,wre);return k.useEffect(()=>{var o,s;const i={nodes:n,edges:r};e==null||e(i),(s=(o=t.getState()).onSelectionChange)==null||s.call(o,i)},[n,r,e]),null});NI.displayName="SelectionListener";const xre=e=>!!e.onSelectionChange;function Cre({onSelectionChange:e}){const t=Vt(xre);return e||t?K.jsx(NI,{onSelectionChange:e}):null}const Tre=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset});function Dl(e,t){k.useEffect(()=>{typeof e<"u"&&t(e)},[e])}function Ae(e,t,n){k.useEffect(()=>{typeof t<"u"&&n({[e]:t})},[t])}const Ere=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:i,onConnectStart:o,onConnectEnd:s,onClickConnectStart:a,onClickConnectEnd:l,nodesDraggable:u,nodesConnectable:c,nodesFocusable:d,edgesFocusable:f,edgesUpdatable:h,elevateNodesOnSelect:p,minZoom:m,maxZoom:S,nodeExtent:v,onNodesChange:y,onEdgesChange:g,elementsSelectable:b,connectionMode:_,snapGrid:w,snapToGrid:x,translateExtent:T,connectOnClick:P,defaultEdgeOptions:E,fitView:A,fitViewOptions:$,onNodesDelete:M,onEdgesDelete:C,onNodeDrag:O,onNodeDragStart:I,onNodeDragStop:N,onSelectionDrag:R,onSelectionDragStart:D,onSelectionDragStop:L,noPanClassName:j,nodeOrigin:U,rfId:G,autoPanOnConnect:W,autoPanOnNodeDrag:X,onError:Y,connectionRadius:B,isValidConnection:H})=>{const{setNodes:Q,setEdges:J,setDefaultNodesAndEdges:ne,setMinZoom:te,setMaxZoom:xe,setTranslateExtent:ve,setNodeExtent:ce,reset:Ne}=Vt(Tre,br),se=Vn();return k.useEffect(()=>{const gt=r==null?void 0:r.map(vn=>({...vn,...E}));return ne(n,gt),()=>{Ne()}},[]),Ae("defaultEdgeOptions",E,se.setState),Ae("connectionMode",_,se.setState),Ae("onConnect",i,se.setState),Ae("onConnectStart",o,se.setState),Ae("onConnectEnd",s,se.setState),Ae("onClickConnectStart",a,se.setState),Ae("onClickConnectEnd",l,se.setState),Ae("nodesDraggable",u,se.setState),Ae("nodesConnectable",c,se.setState),Ae("nodesFocusable",d,se.setState),Ae("edgesFocusable",f,se.setState),Ae("edgesUpdatable",h,se.setState),Ae("elementsSelectable",b,se.setState),Ae("elevateNodesOnSelect",p,se.setState),Ae("snapToGrid",x,se.setState),Ae("snapGrid",w,se.setState),Ae("onNodesChange",y,se.setState),Ae("onEdgesChange",g,se.setState),Ae("connectOnClick",P,se.setState),Ae("fitViewOnInit",A,se.setState),Ae("fitViewOnInitOptions",$,se.setState),Ae("onNodesDelete",M,se.setState),Ae("onEdgesDelete",C,se.setState),Ae("onNodeDrag",O,se.setState),Ae("onNodeDragStart",I,se.setState),Ae("onNodeDragStop",N,se.setState),Ae("onSelectionDrag",R,se.setState),Ae("onSelectionDragStart",D,se.setState),Ae("onSelectionDragStop",L,se.setState),Ae("noPanClassName",j,se.setState),Ae("nodeOrigin",U,se.setState),Ae("rfId",G,se.setState),Ae("autoPanOnConnect",W,se.setState),Ae("autoPanOnNodeDrag",X,se.setState),Ae("onError",Y,se.setState),Ae("connectionRadius",B,se.setState),Ae("isValidConnection",H,se.setState),Dl(e,Q),Dl(t,J),Dl(m,te),Dl(S,xe),Dl(T,ve),Dl(v,ce),null},XT={display:"none"},Pre={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},DI="react-flow__node-desc",LI="react-flow__edge-desc",Are="react-flow__aria-live",kre=e=>e.ariaLiveMessage;function Ore({rfId:e}){const t=Vt(kre);return K.jsx("div",{id:`${Are}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:Pre,children:t})}function Rre({rfId:e,disableKeyboardA11y:t}){return K.jsxs(K.Fragment,{children:[K.jsxs("div",{id:`${DI}-${e}`,style:XT,children:["Press enter or space to select a node.",!t&&"You can then use the arrow keys to move the node around."," Press delete to remove it and escape to cancel."," "]}),K.jsx("div",{id:`${LI}-${e}`,style:XT,children:"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel."}),!t&&K.jsx(Ore,{rfId:e})]})}const Ire=(e,t,n)=>n===pe.Left?e-t:n===pe.Right?e+t:e,Mre=(e,t,n)=>n===pe.Top?e-t:n===pe.Bottom?e+t:e,YT="react-flow__edgeupdater",QT=({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:i,onMouseEnter:o,onMouseOut:s,type:a})=>K.jsx("circle",{onMouseDown:i,onMouseEnter:o,onMouseOut:s,className:ti([YT,`${YT}-${a}`]),cx:Ire(t,r,e),cy:Mre(n,r,e),r,stroke:"transparent",fill:"transparent"}),Nre=()=>!0;var Ll=e=>{const t=({id:n,className:r,type:i,data:o,onClick:s,onEdgeDoubleClick:a,selected:l,animated:u,label:c,labelStyle:d,labelShowBg:f,labelBgStyle:h,labelBgPadding:p,labelBgBorderRadius:m,style:S,source:v,target:y,sourceX:g,sourceY:b,targetX:_,targetY:w,sourcePosition:x,targetPosition:T,elementsSelectable:P,hidden:E,sourceHandleId:A,targetHandleId:$,onContextMenu:M,onMouseEnter:C,onMouseMove:O,onMouseLeave:I,edgeUpdaterRadius:N,onEdgeUpdate:R,onEdgeUpdateStart:D,onEdgeUpdateEnd:L,markerEnd:j,markerStart:U,rfId:G,ariaLabel:W,isFocusable:X,isUpdatable:Y,pathOptions:B,interactionWidth:H})=>{const Q=k.useRef(null),[J,ne]=k.useState(!1),[te,xe]=k.useState(!1),ve=Vn(),ce=k.useMemo(()=>`url(#${n2(U,G)})`,[U,G]),Ne=k.useMemo(()=>`url(#${n2(j,G)})`,[j,G]);if(E)return null;const se=Ht=>{const{edges:xt,addSelectedEdges:wr}=ve.getState();if(P&&(ve.setState({nodesSelectionActive:!1}),wr([n])),s){const $r=xt.find(ri=>ri.id===n);s(Ht,$r)}},gt=qc(n,ve.getState,a),vn=qc(n,ve.getState,M),It=qc(n,ve.getState,C),ut=qc(n,ve.getState,O),Je=qc(n,ve.getState,I),Gt=(Ht,xt)=>{if(Ht.button!==0)return;const{edges:wr,isValidConnection:$r}=ve.getState(),ri=xt?y:v,uo=(xt?$:A)||null,Sn=xt?"target":"source",ii=$r||Nre,ca=xt,ki=wr.find(et=>et.id===n);xe(!0),D==null||D(Ht,ki,Sn);const da=et=>{xe(!1),L==null||L(et,ki,Sn)};PI({event:Ht,handleId:uo,nodeId:ri,onConnect:et=>R==null?void 0:R(ki,et),isTarget:ca,getState:ve.getState,setState:ve.setState,isValidConnection:ii,edgeUpdaterType:Sn,onEdgeUpdateEnd:da})},sr=Ht=>Gt(Ht,!0),ni=Ht=>Gt(Ht,!1),Lr=()=>ne(!0),Rn=()=>ne(!1),bn=!P&&!s,Un=Ht=>{var xt;if(hI.includes(Ht.key)&&P){const{unselectNodesAndEdges:wr,addSelectedEdges:$r,edges:ri}=ve.getState();Ht.key==="Escape"?((xt=Q.current)==null||xt.blur(),wr({edges:[ri.find(Sn=>Sn.id===n)]})):$r([n])}};return K.jsxs("g",{className:ti(["react-flow__edge",`react-flow__edge-${i}`,r,{selected:l,animated:u,inactive:bn,updating:J}]),onClick:se,onDoubleClick:gt,onContextMenu:vn,onMouseEnter:It,onMouseMove:ut,onMouseLeave:Je,onKeyDown:X?Un:void 0,tabIndex:X?0:void 0,role:X?"button":void 0,"data-testid":`rf__edge-${n}`,"aria-label":W===null?void 0:W||`Edge from ${v} to ${y}`,"aria-describedby":X?`${LI}-${G}`:void 0,ref:Q,children:[!te&&K.jsx(e,{id:n,source:v,target:y,selected:l,animated:u,label:c,labelStyle:d,labelShowBg:f,labelBgStyle:h,labelBgPadding:p,labelBgBorderRadius:m,data:o,style:S,sourceX:g,sourceY:b,targetX:_,targetY:w,sourcePosition:x,targetPosition:T,sourceHandleId:A,targetHandleId:$,markerStart:ce,markerEnd:Ne,pathOptions:B,interactionWidth:H}),Y&&K.jsxs(K.Fragment,{children:[(Y==="source"||Y===!0)&&K.jsx(QT,{position:x,centerX:g,centerY:b,radius:N,onMouseDown:sr,onMouseEnter:Lr,onMouseOut:Rn,type:"source"}),(Y==="target"||Y===!0)&&K.jsx(QT,{position:T,centerX:_,centerY:w,radius:N,onMouseDown:ni,onMouseEnter:Lr,onMouseOut:Rn,type:"target"})]})]})};return t.displayName="EdgeWrapper",k.memo(t)};function Dre(e){const t={default:Ll(e.default||$m),straight:Ll(e.bezier||nC),step:Ll(e.step||tC),smoothstep:Ll(e.step||I0),simplebezier:Ll(e.simplebezier||eC)},n={},r=Object.keys(e).filter(i=>!["default","bezier"].includes(i)).reduce((i,o)=>(i[o]=Ll(e[o]||$m),i),n);return{...t,...r}}function ZT(e,t,n=null){const r=((n==null?void 0:n.x)||0)+t.x,i=((n==null?void 0:n.y)||0)+t.y,o=(n==null?void 0:n.width)||t.width,s=(n==null?void 0:n.height)||t.height;switch(e){case pe.Top:return{x:r+o/2,y:i};case pe.Right:return{x:r+o,y:i+s/2};case pe.Bottom:return{x:r+o/2,y:i+s};case pe.Left:return{x:r,y:i+s/2}}}function JT(e,t){return e?e.length===1||!t?e[0]:t&&e.find(n=>n.id===t)||null:null}const Lre=(e,t,n,r,i,o)=>{const s=ZT(n,e,t),a=ZT(o,r,i);return{sourceX:s.x,sourceY:s.y,targetX:a.x,targetY:a.y}};function $re({sourcePos:e,targetPos:t,sourceWidth:n,sourceHeight:r,targetWidth:i,targetHeight:o,width:s,height:a,transform:l}){const u={x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x+n,t.x+i),y2:Math.max(e.y+r,t.y+o)};u.x===u.x2&&(u.x2+=1),u.y===u.y2&&(u.y2+=1);const c=Dm({x:(0-l[0])/l[2],y:(0-l[1])/l[2],width:s/l[2],height:a/l[2]}),d=Math.max(0,Math.min(c.x2,u.x2)-Math.max(c.x,u.x)),f=Math.max(0,Math.min(c.y2,u.y2)-Math.max(c.y,u.y));return Math.ceil(d*f)>0}function eE(e){var r,i,o,s,a;const t=((r=e==null?void 0:e[on])==null?void 0:r.handleBounds)||null,n=t&&(e==null?void 0:e.width)&&(e==null?void 0:e.height)&&typeof((i=e==null?void 0:e.positionAbsolute)==null?void 0:i.x)<"u"&&typeof((o=e==null?void 0:e.positionAbsolute)==null?void 0:o.y)<"u";return[{x:((s=e==null?void 0:e.positionAbsolute)==null?void 0:s.x)||0,y:((a=e==null?void 0:e.positionAbsolute)==null?void 0:a.y)||0,width:(e==null?void 0:e.width)||0,height:(e==null?void 0:e.height)||0},t,!!n]}function $I(e,t){if(!e.parentNode)return!1;const n=t.get(e.parentNode);return n?n.selected?!0:$I(n,t):!1}function tE(e,t,n){let r=e;do{if(r!=null&&r.matches(t))return!0;if(r===n.current)return!1;r=r.parentElement}while(r);return!1}function Fre(e,t,n,r){return Array.from(e.values()).filter(i=>(i.selected||i.id===r)&&(!i.parentNode||!$I(i,e))&&(i.draggable||t&&typeof i.draggable>"u")).map(i=>{var o,s;return{id:i.id,position:i.position||{x:0,y:0},positionAbsolute:i.positionAbsolute||{x:0,y:0},distance:{x:n.x-(((o=i.positionAbsolute)==null?void 0:o.x)??0),y:n.y-(((s=i.positionAbsolute)==null?void 0:s.y)??0)},delta:{x:0,y:0},extent:i.extent,parentNode:i.parentNode,width:i.width,height:i.height}})}function Bre(e,t){return!t||t==="parent"?t:[t[0],[t[1][0]-(e.width||0),t[1][1]-(e.height||0)]]}function FI(e,t,n,r,i=[0,0],o){const s=Bre(e,e.extent||r);let a=s;if(e.extent==="parent")if(e.parentNode&&e.width&&e.height){const c=n.get(e.parentNode),{x:d,y:f}=Mu(c,i).positionAbsolute;a=c&&Kr(d)&&Kr(f)&&Kr(c.width)&&Kr(c.height)?[[d+e.width*i[0],f+e.height*i[1]],[d+c.width-e.width+e.width*i[0],f+c.height-e.height+e.height*i[1]]]:a}else o==null||o("005",qs.error005()),a=s;else if(e.extent&&e.parentNode){const c=n.get(e.parentNode),{x:d,y:f}=Mu(c,i).positionAbsolute;a=[[e.extent[0][0]+d,e.extent[0][1]+f],[e.extent[1][0]+d,e.extent[1][1]+f]]}let l={x:0,y:0};if(e.parentNode){const c=n.get(e.parentNode);l=Mu(c,i).positionAbsolute}const u=a?Jx(t,a):t;return{position:{x:u.x-l.x,y:u.y-l.y},positionAbsolute:u}}function Pb({nodeId:e,dragItems:t,nodeInternals:n}){const r=t.map(i=>({...n.get(i.id),position:i.position,positionAbsolute:i.positionAbsolute}));return[e?r.find(i=>i.id===e):r[0],r]}const nE=(e,t,n,r)=>{const i=t.querySelectorAll(e);if(!i||!i.length)return null;const o=Array.from(i),s=t.getBoundingClientRect(),a={x:s.width*r[0],y:s.height*r[1]};return o.map(l=>{const u=l.getBoundingClientRect();return{id:l.getAttribute("data-handleid"),position:l.getAttribute("data-handlepos"),x:(u.left-s.left-a.x)/n,y:(u.top-s.top-a.y)/n,...Zx(l)}})};function Wc(e,t,n){return n===void 0?n:r=>{const i=t().nodeInternals.get(e);n(r,{...i})}}function i2({id:e,store:t,unselect:n=!1,nodeRef:r}){const{addSelectedNodes:i,unselectNodesAndEdges:o,multiSelectionActive:s,nodeInternals:a}=t.getState(),l=a.get(e);t.setState({nodesSelectionActive:!1}),l.selected?(n||l.selected&&s)&&(o({nodes:[l]}),requestAnimationFrame(()=>{var u;return(u=r==null?void 0:r.current)==null?void 0:u.blur()})):i([e])}function jre(){const e=Vn();return k.useCallback(({sourceEvent:n})=>{const{transform:r,snapGrid:i,snapToGrid:o}=e.getState(),s=n.touches?n.touches[0].clientX:n.clientX,a=n.touches?n.touches[0].clientY:n.clientY,l={x:(s-r[0])/r[2],y:(a-r[1])/r[2]};return{xSnapped:o?i[0]*Math.round(l.x/i[0]):l.x,ySnapped:o?i[1]*Math.round(l.y/i[1]):l.y,...l}},[])}function Ab(e){return(t,n,r)=>e==null?void 0:e(t,r)}function BI({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:i,isSelectable:o,selectNodesOnDrag:s}){const a=Vn(),[l,u]=k.useState(!1),c=k.useRef([]),d=k.useRef({x:null,y:null}),f=k.useRef(0),h=k.useRef(null),p=k.useRef({x:0,y:0}),m=k.useRef(null),S=k.useRef(!1),v=jre();return k.useEffect(()=>{if(e!=null&&e.current){const y=fi(e.current),g=({x:_,y:w})=>{const{nodeInternals:x,onNodeDrag:T,onSelectionDrag:P,updateNodePositions:E,nodeExtent:A,snapGrid:$,snapToGrid:M,nodeOrigin:C,onError:O}=a.getState();d.current={x:_,y:w};let I=!1;if(c.current=c.current.map(R=>{const D={x:_-R.distance.x,y:w-R.distance.y};M&&(D.x=$[0]*Math.round(D.x/$[0]),D.y=$[1]*Math.round(D.y/$[1]));const L=FI(R,D,x,A,C,O);return I=I||R.position.x!==L.position.x||R.position.y!==L.position.y,R.position=L.position,R.positionAbsolute=L.positionAbsolute,R}),!I)return;E(c.current,!0,!0),u(!0);const N=i?T:Ab(P);if(N&&m.current){const[R,D]=Pb({nodeId:i,dragItems:c.current,nodeInternals:x});N(m.current,R,D)}},b=()=>{if(!h.current)return;const[_,w]=uI(p.current,h.current);if(_!==0||w!==0){const{transform:x,panBy:T}=a.getState();d.current.x=(d.current.x??0)-_/x[2],d.current.y=(d.current.y??0)-w/x[2],T({x:_,y:w})&&g(d.current)}f.current=requestAnimationFrame(b)};if(t)y.on(".drag",null);else{const _=ote().on("start",w=>{var I;const{nodeInternals:x,multiSelectionActive:T,domNode:P,nodesDraggable:E,unselectNodesAndEdges:A,onNodeDragStart:$,onSelectionDragStart:M}=a.getState(),C=i?$:Ab(M);!s&&!T&&i&&((I=x.get(i))!=null&&I.selected||A()),i&&o&&s&&i2({id:i,store:a,nodeRef:e});const O=v(w);if(d.current=O,c.current=Fre(x,E,O,i),C&&c.current){const[N,R]=Pb({nodeId:i,dragItems:c.current,nodeInternals:x});C(w.sourceEvent,N,R)}h.current=(P==null?void 0:P.getBoundingClientRect())||null,p.current=Ms(w.sourceEvent,h.current)}).on("drag",w=>{const x=v(w),{autoPanOnNodeDrag:T}=a.getState();!S.current&&T&&(S.current=!0,b()),(d.current.x!==x.xSnapped||d.current.y!==x.ySnapped)&&c.current&&(m.current=w.sourceEvent,p.current=Ms(w.sourceEvent,h.current),g(x))}).on("end",w=>{if(u(!1),S.current=!1,cancelAnimationFrame(f.current),c.current){const{updateNodePositions:x,nodeInternals:T,onNodeDragStop:P,onSelectionDragStop:E}=a.getState(),A=i?P:Ab(E);if(x(c.current,!1,!1),A){const[$,M]=Pb({nodeId:i,dragItems:c.current,nodeInternals:T});A(w.sourceEvent,$,M)}}}).filter(w=>{const x=w.target;return!w.button&&(!n||!tE(x,`.${n}`,e))&&(!r||tE(x,r,e))});return y.call(_),()=>{y.on(".drag",null)}}}},[e,t,n,r,o,a,i,s,v]),l}function jI(){const e=Vn();return k.useCallback(n=>{const{nodeInternals:r,nodeExtent:i,updateNodePositions:o,getNodes:s,snapToGrid:a,snapGrid:l,onError:u,nodesDraggable:c}=e.getState(),d=s().filter(y=>y.selected&&(y.draggable||c&&typeof y.draggable>"u")),f=a?l[0]:5,h=a?l[1]:5,p=n.isShiftPressed?4:1,m=n.x*f*p,S=n.y*h*p,v=d.map(y=>{if(y.positionAbsolute){const g={x:y.positionAbsolute.x+m,y:y.positionAbsolute.y+S};a&&(g.x=l[0]*Math.round(g.x/l[0]),g.y=l[1]*Math.round(g.y/l[1]));const{positionAbsolute:b,position:_}=FI(y,g,r,i,void 0,u);y.position=_,y.positionAbsolute=b}return y});o(v,!0,!1)},[])}const Nu={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}};var Kc=e=>{const t=({id:n,type:r,data:i,xPos:o,yPos:s,xPosOrigin:a,yPosOrigin:l,selected:u,onClick:c,onMouseEnter:d,onMouseMove:f,onMouseLeave:h,onContextMenu:p,onDoubleClick:m,style:S,className:v,isDraggable:y,isSelectable:g,isConnectable:b,isFocusable:_,selectNodesOnDrag:w,sourcePosition:x,targetPosition:T,hidden:P,resizeObserver:E,dragHandle:A,zIndex:$,isParent:M,noDragClassName:C,noPanClassName:O,initialized:I,disableKeyboardA11y:N,ariaLabel:R,rfId:D})=>{const L=Vn(),j=k.useRef(null),U=k.useRef(x),G=k.useRef(T),W=k.useRef(r),X=g||y||c||d||f||h,Y=jI(),B=Wc(n,L.getState,d),H=Wc(n,L.getState,f),Q=Wc(n,L.getState,h),J=Wc(n,L.getState,p),ne=Wc(n,L.getState,m),te=ce=>{if(g&&(!w||!y)&&i2({id:n,store:L,nodeRef:j}),c){const Ne=L.getState().nodeInternals.get(n);c(ce,{...Ne})}},xe=ce=>{if(!e2(ce))if(hI.includes(ce.key)&&g){const Ne=ce.key==="Escape";i2({id:n,store:L,unselect:Ne,nodeRef:j})}else!N&&y&&u&&Object.prototype.hasOwnProperty.call(Nu,ce.key)&&(L.setState({ariaLiveMessage:`Moved selected node ${ce.key.replace("Arrow","").toLowerCase()}. New position, x: ${~~o}, y: ${~~s}`}),Y({x:Nu[ce.key].x,y:Nu[ce.key].y,isShiftPressed:ce.shiftKey}))};k.useEffect(()=>{if(j.current&&!P){const ce=j.current;return E==null||E.observe(ce),()=>E==null?void 0:E.unobserve(ce)}},[P]),k.useEffect(()=>{const ce=W.current!==r,Ne=U.current!==x,se=G.current!==T;j.current&&(ce||Ne||se)&&(ce&&(W.current=r),Ne&&(U.current=x),se&&(G.current=T),L.getState().updateNodeDimensions([{id:n,nodeElement:j.current,forceUpdate:!0}]))},[n,r,x,T]);const ve=BI({nodeRef:j,disabled:P||!y,noDragClassName:C,handleSelector:A,nodeId:n,isSelectable:g,selectNodesOnDrag:w});return P?null:K.jsx("div",{className:ti(["react-flow__node",`react-flow__node-${r}`,{[O]:y},v,{selected:u,selectable:g,parent:M,dragging:ve}]),ref:j,style:{zIndex:$,transform:`translate(${a}px,${l}px)`,pointerEvents:X?"all":"none",visibility:I?"visible":"hidden",...S},"data-id":n,"data-testid":`rf__node-${n}`,onMouseEnter:B,onMouseMove:H,onMouseLeave:Q,onContextMenu:J,onClick:te,onDoubleClick:ne,onKeyDown:_?xe:void 0,tabIndex:_?0:void 0,role:_?"button":void 0,"aria-describedby":N?void 0:`${DI}-${D}`,"aria-label":R,children:K.jsx(ure,{value:n,children:K.jsx(e,{id:n,data:i,type:r,xPos:o,yPos:s,selected:u,isConnectable:b,sourcePosition:x,targetPosition:T,dragging:ve,dragHandle:A,zIndex:$})})})};return t.displayName="NodeWrapper",k.memo(t)};function Vre(e){const t={input:Kc(e.input||RI),default:Kc(e.default||r2),output:Kc(e.output||MI),group:Kc(e.group||oC)},n={},r=Object.keys(e).filter(i=>!["input","default","output","group"].includes(i)).reduce((i,o)=>(i[o]=Kc(e[o]||r2),i),n);return{...t,...r}}const zre=({x:e,y:t,width:n,height:r,origin:i})=>!n||!r?{x:e,y:t}:i[0]<0||i[1]<0||i[0]>1||i[1]>1?{x:e,y:t}:{x:e-n*i[0],y:t-r*i[1]},Ure=typeof document<"u"?document:null;var Nf=(e=null,t={target:Ure})=>{const[n,r]=k.useState(!1),i=k.useRef(!1),o=k.useRef(new Set([])),[s,a]=k.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(d=>typeof d=="string").map(d=>d.split("+")),c=u.reduce((d,f)=>d.concat(...f),[]);return[u,c]}return[[],[]]},[e]);return k.useEffect(()=>{var l,u;if(e!==null){const c=h=>{if(i.current=h.ctrlKey||h.metaKey||h.shiftKey,!i.current&&e2(h))return!1;const p=iE(h.code,a);o.current.add(h[p]),rE(s,o.current,!1)&&(h.preventDefault(),r(!0))},d=h=>{if(!i.current&&e2(h))return!1;const p=iE(h.code,a);rE(s,o.current,!0)?(r(!1),o.current.clear()):o.current.delete(h[p]),i.current=!1},f=()=>{o.current.clear(),r(!1)};return(l=t==null?void 0:t.target)==null||l.addEventListener("keydown",c),(u=t==null?void 0:t.target)==null||u.addEventListener("keyup",d),window.addEventListener("blur",f),()=>{var h,p;(h=t==null?void 0:t.target)==null||h.removeEventListener("keydown",c),(p=t==null?void 0:t.target)==null||p.removeEventListener("keyup",d),window.removeEventListener("blur",f)}}},[e,r]),n};function rE(e,t,n){return e.filter(r=>n||r.length===t.size).some(r=>r.every(i=>t.has(i)))}function iE(e,t){return t.includes(e)?"code":"key"}function VI(e,t,n,r){var s,a;if(!e.parentNode)return n;const i=t.get(e.parentNode),o=Mu(i,r);return VI(i,t,{x:(n.x??0)+o.x,y:(n.y??0)+o.y,z:(((s=i[on])==null?void 0:s.z)??0)>(n.z??0)?((a=i[on])==null?void 0:a.z)??0:n.z??0},r)}function zI(e,t,n){e.forEach(r=>{var i;if(r.parentNode&&!e.has(r.parentNode))throw new Error(`Parent node ${r.parentNode} not found`);if(r.parentNode||n!=null&&n[r.id]){const{x:o,y:s,z:a}=VI(r,e,{...r.position,z:((i=r[on])==null?void 0:i.z)??0},t);r.positionAbsolute={x:o,y:s},r[on].z=a,n!=null&&n[r.id]&&(r[on].isParent=!0)}})}function kb(e,t,n,r){const i=new Map,o={},s=r?1e3:0;return e.forEach(a=>{var d;const l=(Kr(a.zIndex)?a.zIndex:0)+(a.selected?s:0),u=t.get(a.id),c={width:u==null?void 0:u.width,height:u==null?void 0:u.height,...a,positionAbsolute:{x:a.position.x,y:a.position.y}};a.parentNode&&(c.parentNode=a.parentNode,o[a.parentNode]=!0),Object.defineProperty(c,on,{enumerable:!1,value:{handleBounds:(d=u==null?void 0:u[on])==null?void 0:d.handleBounds,z:l}}),i.set(a.id,c)}),zI(i,n,o),i}function UI(e,t={}){const{getNodes:n,width:r,height:i,minZoom:o,maxZoom:s,d3Zoom:a,d3Selection:l,fitViewOnInitDone:u,fitViewOnInit:c,nodeOrigin:d}=e(),f=t.initial&&!u&&c;if(a&&l&&(f||!t.initial)){const p=n().filter(S=>{var y;const v=t.includeHiddenNodes?S.width&&S.height:!S.hidden;return(y=t.nodes)!=null&&y.length?v&&t.nodes.some(g=>g.id===S.id):v}),m=p.every(S=>S.width&&S.height);if(p.length>0&&m){const S=_I(p,d),[v,y,g]=CI(S,r,i,t.minZoom??o,t.maxZoom??s,t.padding??.1),b=Is.translate(v,y).scale(g);return typeof t.duration=="number"&&t.duration>0?a.transform(xa(l,t.duration),b):a.transform(l,b),!0}}return!1}function Gre(e,t){return e.forEach(n=>{const r=t.get(n.id);r&&t.set(r.id,{...r,[on]:r[on],selected:n.selected})}),new Map(t)}function Hre(e,t){return t.map(n=>{const r=e.find(i=>i.id===n.id);return r&&(n.selected=r.selected),n})}function kp({changedNodes:e,changedEdges:t,get:n,set:r}){const{nodeInternals:i,edges:o,onNodesChange:s,onEdgesChange:a,hasDefaultNodes:l,hasDefaultEdges:u}=n();e!=null&&e.length&&(l&&r({nodeInternals:Gre(e,i)}),s==null||s(e)),t!=null&&t.length&&(u&&r({edges:Hre(t,o)}),a==null||a(t))}const $l=()=>{},qre={zoomIn:$l,zoomOut:$l,zoomTo:$l,getZoom:()=>1,setViewport:$l,getViewport:()=>({x:0,y:0,zoom:1}),fitView:()=>!1,setCenter:$l,fitBounds:$l,project:e=>e,viewportInitialized:!1},Wre=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection}),Kre=()=>{const e=Vn(),{d3Zoom:t,d3Selection:n}=Vt(Wre,br);return k.useMemo(()=>n&&t?{zoomIn:i=>t.scaleBy(xa(n,i==null?void 0:i.duration),1.2),zoomOut:i=>t.scaleBy(xa(n,i==null?void 0:i.duration),1/1.2),zoomTo:(i,o)=>t.scaleTo(xa(n,o==null?void 0:o.duration),i),getZoom:()=>e.getState().transform[2],setViewport:(i,o)=>{const[s,a,l]=e.getState().transform,u=Is.translate(i.x??s,i.y??a).scale(i.zoom??l);t.transform(xa(n,o==null?void 0:o.duration),u)},getViewport:()=>{const[i,o,s]=e.getState().transform;return{x:i,y:o,zoom:s}},fitView:i=>UI(e.getState,i),setCenter:(i,o,s)=>{const{width:a,height:l,maxZoom:u}=e.getState(),c=typeof(s==null?void 0:s.zoom)<"u"?s.zoom:u,d=a/2-i*c,f=l/2-o*c,h=Is.translate(d,f).scale(c);t.transform(xa(n,s==null?void 0:s.duration),h)},fitBounds:(i,o)=>{const{width:s,height:a,minZoom:l,maxZoom:u}=e.getState(),[c,d,f]=CI(i,s,a,l,u,(o==null?void 0:o.padding)??.1),h=Is.translate(c,d).scale(f);t.transform(xa(n,o==null?void 0:o.duration),h)},project:i=>{const{transform:o,snapToGrid:s,snapGrid:a}=e.getState();return SI(i,o,s,a)},viewportInitialized:!0}:qre,[t,n])};function GI(){const e=Kre(),t=Vn(),n=k.useCallback(()=>t.getState().getNodes().map(m=>({...m})),[]),r=k.useCallback(m=>t.getState().nodeInternals.get(m),[]),i=k.useCallback(()=>{const{edges:m=[]}=t.getState();return m.map(S=>({...S}))},[]),o=k.useCallback(m=>{const{edges:S=[]}=t.getState();return S.find(v=>v.id===m)},[]),s=k.useCallback(m=>{const{getNodes:S,setNodes:v,hasDefaultNodes:y,onNodesChange:g}=t.getState(),b=S(),_=typeof m=="function"?m(b):m;if(y)v(_);else if(g){const w=_.length===0?b.map(x=>({type:"remove",id:x.id})):_.map(x=>({item:x,type:"reset"}));g(w)}},[]),a=k.useCallback(m=>{const{edges:S=[],setEdges:v,hasDefaultEdges:y,onEdgesChange:g}=t.getState(),b=typeof m=="function"?m(S):m;if(y)v(b);else if(g){const _=b.length===0?S.map(w=>({type:"remove",id:w.id})):b.map(w=>({item:w,type:"reset"}));g(_)}},[]),l=k.useCallback(m=>{const S=Array.isArray(m)?m:[m],{getNodes:v,setNodes:y,hasDefaultNodes:g,onNodesChange:b}=t.getState();if(g){const w=[...v(),...S];y(w)}else if(b){const _=S.map(w=>({item:w,type:"add"}));b(_)}},[]),u=k.useCallback(m=>{const S=Array.isArray(m)?m:[m],{edges:v=[],setEdges:y,hasDefaultEdges:g,onEdgesChange:b}=t.getState();if(g)y([...v,...S]);else if(b){const _=S.map(w=>({item:w,type:"add"}));b(_)}},[]),c=k.useCallback(()=>{const{getNodes:m,edges:S=[],transform:v}=t.getState(),[y,g,b]=v;return{nodes:m().map(_=>({..._})),edges:S.map(_=>({..._})),viewport:{x:y,y:g,zoom:b}}},[]),d=k.useCallback(({nodes:m,edges:S})=>{const{nodeInternals:v,getNodes:y,edges:g,hasDefaultNodes:b,hasDefaultEdges:_,onNodesDelete:w,onEdgesDelete:x,onNodesChange:T,onEdgesChange:P}=t.getState(),E=(m||[]).map(O=>O.id),A=(S||[]).map(O=>O.id),$=y().reduce((O,I)=>{const N=!E.includes(I.id)&&I.parentNode&&O.find(D=>D.id===I.parentNode);return(typeof I.deletable=="boolean"?I.deletable:!0)&&(E.includes(I.id)||N)&&O.push(I),O},[]),M=g.filter(O=>typeof O.deletable=="boolean"?O.deletable:!0),C=M.filter(O=>A.includes(O.id));if($||C){const O=xI($,M),I=[...C,...O],N=I.reduce((R,D)=>(R.includes(D.id)||R.push(D.id),R),[]);if((_||b)&&(_&&t.setState({edges:g.filter(R=>!N.includes(R.id))}),b&&($.forEach(R=>{v.delete(R.id)}),t.setState({nodeInternals:new Map(v)}))),N.length>0&&(x==null||x(I),P&&P(N.map(R=>({id:R,type:"remove"})))),$.length>0&&(w==null||w($),T)){const R=$.map(D=>({id:D.id,type:"remove"}));T(R)}}},[]),f=k.useCallback(m=>{const S=nre(m),v=S?null:t.getState().nodeInternals.get(m.id);return[S?m:zT(v),v,S]},[]),h=k.useCallback((m,S=!0,v)=>{const[y,g,b]=f(m);return y?(v||t.getState().getNodes()).filter(_=>{if(!b&&(_.id===g.id||!_.positionAbsolute))return!1;const w=zT(_),x=J_(w,y);return S&&x>0||x>=m.width*m.height}):[]},[]),p=k.useCallback((m,S,v=!0)=>{const[y]=f(m);if(!y)return!1;const g=J_(y,S);return v&&g>0||g>=m.width*m.height},[]);return k.useMemo(()=>({...e,getNodes:n,getNode:r,getEdges:i,getEdge:o,setNodes:s,setEdges:a,addNodes:l,addEdges:u,toObject:c,deleteElements:d,getIntersectingNodes:h,isNodeIntersecting:p}),[e,n,r,i,o,s,a,l,u,c,d,h,p])}var Xre=({deleteKeyCode:e,multiSelectionKeyCode:t})=>{const n=Vn(),{deleteElements:r}=GI(),i=Nf(e),o=Nf(t);k.useEffect(()=>{if(i){const{edges:s,getNodes:a}=n.getState(),l=a().filter(c=>c.selected),u=s.filter(c=>c.selected);r({nodes:l,edges:u}),n.setState({nodesSelectionActive:!1})}},[i]),k.useEffect(()=>{n.setState({multiSelectionActive:o})},[o])};function Yre(e){const t=Vn();k.useEffect(()=>{let n;const r=()=>{var o,s;if(!e.current)return;const i=Zx(e.current);(i.height===0||i.width===0)&&((s=(o=t.getState()).onError)==null||s.call(o,"004",qs.error004())),t.setState({width:i.width||500,height:i.height||500})};return r(),window.addEventListener("resize",r),e.current&&(n=new ResizeObserver(()=>r()),n.observe(e.current)),()=>{window.removeEventListener("resize",r),n&&e.current&&n.unobserve(e.current)}},[])}const sC={position:"absolute",width:"100%",height:"100%",top:0,left:0},Qre=(e,t)=>e.x!==t.x||e.y!==t.y||e.zoom!==t.k,Ob=e=>({x:e.x,y:e.y,zoom:e.k}),Fl=(e,t)=>e.target.closest(`.${t}`),oE=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Zre=e=>({d3Zoom:e.d3Zoom,d3Selection:e.d3Selection,d3ZoomHandler:e.d3ZoomHandler,userSelectionActive:e.userSelectionActive}),Jre=({onMove:e,onMoveStart:t,onMoveEnd:n,onPaneContextMenu:r,zoomOnScroll:i=!0,zoomOnPinch:o=!0,panOnScroll:s=!1,panOnScrollSpeed:a=.5,panOnScrollMode:l=Iu.Free,zoomOnDoubleClick:u=!0,elementsSelectable:c,panOnDrag:d=!0,defaultViewport:f,translateExtent:h,minZoom:p,maxZoom:m,zoomActivationKeyCode:S,preventScrolling:v=!0,children:y,noWheelClassName:g,noPanClassName:b})=>{const _=k.useRef(),w=Vn(),x=k.useRef(!1),T=k.useRef(!1),P=k.useRef(null),E=k.useRef({x:0,y:0,zoom:0}),{d3Zoom:A,d3Selection:$,d3ZoomHandler:M,userSelectionActive:C}=Vt(Zre,br),O=Nf(S),I=k.useRef(0);return Yre(P),k.useEffect(()=>{if(P.current){const N=P.current.getBoundingClientRect(),R=Xne().scaleExtent([p,m]).translateExtent(h),D=fi(P.current).call(R),L=Is.translate(f.x,f.y).scale(rc(f.zoom,p,m)),j=[[0,0],[N.width,N.height]],U=R.constrain()(L,j,h);R.transform(D,U),w.setState({d3Zoom:R,d3Selection:D,d3ZoomHandler:D.on("wheel.zoom"),transform:[U.x,U.y,U.k],domNode:P.current.closest(".react-flow")})}},[]),k.useEffect(()=>{$&&A&&(s&&!O&&!C?$.on("wheel.zoom",N=>{if(Fl(N,g))return!1;N.preventDefault(),N.stopImmediatePropagation();const R=$.property("__zoom").k||1;if(N.ctrlKey&&o){const U=$i(N),G=-N.deltaY*(N.deltaMode===1?.05:N.deltaMode?1:.002)*10,W=R*Math.pow(2,G);A.scaleTo($,W,U);return}const D=N.deltaMode===1?20:1,L=l===Iu.Vertical?0:N.deltaX*D,j=l===Iu.Horizontal?0:N.deltaY*D;A.translateBy($,-(L/R)*a,-(j/R)*a)},{passive:!1}):typeof M<"u"&&$.on("wheel.zoom",function(N,R){if(!v||Fl(N,g))return null;N.preventDefault(),M.call(this,N,R)},{passive:!1}))},[C,s,l,$,A,M,O,o,v,g]),k.useEffect(()=>{A&&A.on("start",N=>{var D;if(!N.sourceEvent)return null;I.current=N.sourceEvent.button;const{onViewportChangeStart:R}=w.getState();if(x.current=!0,((D=N.sourceEvent)==null?void 0:D.type)==="mousedown"&&w.setState({paneDragging:!0}),t||R){const L=Ob(N.transform);E.current=L,R==null||R(L),t==null||t(N.sourceEvent,L)}})},[A,t]),k.useEffect(()=>{A&&(C&&!x.current?A.on("zoom",null):C||A.on("zoom",N=>{const{onViewportChange:R}=w.getState();if(w.setState({transform:[N.transform.x,N.transform.y,N.transform.k]}),T.current=!!(r&&oE(d,I.current??0)),e||R){const D=Ob(N.transform);R==null||R(D),e==null||e(N.sourceEvent,D)}}))},[C,A,e,d,r]),k.useEffect(()=>{A&&A.on("end",N=>{if(!N.sourceEvent)return null;const{onViewportChangeEnd:R}=w.getState();if(x.current=!1,w.setState({paneDragging:!1}),r&&oE(d,I.current??0)&&!T.current&&r(N.sourceEvent),T.current=!1,(n||R)&&Qre(E.current,N.transform)){const D=Ob(N.transform);E.current=D,clearTimeout(_.current),_.current=setTimeout(()=>{R==null||R(D),n==null||n(N.sourceEvent,D)},s?150:0)}})},[A,s,d,n,r]),k.useEffect(()=>{A&&A.filter(N=>{const R=O||i,D=o&&N.ctrlKey;if(N.button===1&&N.type==="mousedown"&&(Fl(N,"react-flow__node")||Fl(N,"react-flow__edge")))return!0;if(!d&&!R&&!s&&!u&&!o||C||!u&&N.type==="dblclick"||Fl(N,g)&&N.type==="wheel"||Fl(N,b)&&N.type!=="wheel"||!o&&N.ctrlKey&&N.type==="wheel"||!R&&!s&&!D&&N.type==="wheel"||!d&&(N.type==="mousedown"||N.type==="touchstart")||Array.isArray(d)&&!d.includes(N.button)&&(N.type==="mousedown"||N.type==="touchstart"))return!1;const L=Array.isArray(d)&&d.includes(N.button)||!N.button||N.button<=1;return(!N.ctrlKey||N.type==="wheel")&&L})},[C,A,i,o,s,u,d,c,O]),K.jsx("div",{className:"react-flow__renderer",ref:P,style:sC,children:y})},eie=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function tie(){const{userSelectionActive:e,userSelectionRect:t}=Vt(eie,br);return e&&t?K.jsx("div",{className:"react-flow__selection react-flow__container",style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}function sE(e,t){const n=e.find(r=>r.id===t.parentNode);if(n){const r=t.position.x+t.width-n.width,i=t.position.y+t.height-n.height;if(r>0||i>0||t.position.x<0||t.position.y<0){if(n.style={...n.style},n.style.width=n.style.width??n.width,n.style.height=n.style.height??n.height,r>0&&(n.style.width+=r),i>0&&(n.style.height+=i),t.position.x<0){const o=Math.abs(t.position.x);n.position.x=n.position.x-o,n.style.width+=o,t.position.x=0}if(t.position.y<0){const o=Math.abs(t.position.y);n.position.y=n.position.y-o,n.style.height+=o,t.position.y=0}n.width=n.style.width,n.height=n.style.height}}}function HI(e,t){if(e.some(r=>r.type==="reset"))return e.filter(r=>r.type==="reset").map(r=>r.item);const n=e.filter(r=>r.type==="add").map(r=>r.item);return t.reduce((r,i)=>{const o=e.filter(a=>a.id===i.id);if(o.length===0)return r.push(i),r;const s={...i};for(const a of o)if(a)switch(a.type){case"select":{s.selected=a.selected;break}case"position":{typeof a.position<"u"&&(s.position=a.position),typeof a.positionAbsolute<"u"&&(s.positionAbsolute=a.positionAbsolute),typeof a.dragging<"u"&&(s.dragging=a.dragging),s.expandParent&&sE(r,s);break}case"dimensions":{typeof a.dimensions<"u"&&(s.width=a.dimensions.width,s.height=a.dimensions.height),typeof a.updateStyle<"u"&&(s.style={...s.style||{},...a.dimensions}),typeof a.resizing=="boolean"&&(s.resizing=a.resizing),s.expandParent&&sE(r,s);break}case"remove":return r}return r.push(s),r},n)}function qI(e,t){return HI(e,t)}function nie(e,t){return HI(e,t)}const ds=(e,t)=>({id:e,type:"select",selected:t});function du(e,t){return e.reduce((n,r)=>{const i=t.includes(r.id);return!r.selected&&i?(r.selected=!0,n.push(ds(r.id,!0))):r.selected&&!i&&(r.selected=!1,n.push(ds(r.id,!1))),n},[])}const Rb=(e,t)=>n=>{n.target===t.current&&(e==null||e(n))},rie=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,dragging:e.paneDragging}),WI=k.memo(({isSelecting:e,selectionMode:t=Mf.Full,panOnDrag:n,onSelectionStart:r,onSelectionEnd:i,onPaneClick:o,onPaneContextMenu:s,onPaneScroll:a,onPaneMouseEnter:l,onPaneMouseMove:u,onPaneMouseLeave:c,children:d})=>{const f=k.useRef(null),h=Vn(),p=k.useRef(0),m=k.useRef(0),S=k.useRef(),{userSelectionActive:v,elementsSelectable:y,dragging:g}=Vt(rie,br),b=()=>{h.setState({userSelectionActive:!1,userSelectionRect:null}),p.current=0,m.current=0},_=M=>{o==null||o(M),h.getState().resetSelectedElements(),h.setState({nodesSelectionActive:!1})},w=M=>{if(Array.isArray(n)&&(n!=null&&n.includes(2))){M.preventDefault();return}s==null||s(M)},x=a?M=>a(M):void 0,T=M=>{const{resetSelectedElements:C,domNode:O}=h.getState();if(S.current=O==null?void 0:O.getBoundingClientRect(),!y||!e||M.button!==0||M.target!==f.current||!S.current)return;const{x:I,y:N}=Ms(M,S.current);C(),h.setState({userSelectionRect:{width:0,height:0,startX:I,startY:N,x:I,y:N}}),r==null||r(M)},P=M=>{const{userSelectionRect:C,nodeInternals:O,edges:I,transform:N,onNodesChange:R,onEdgesChange:D,nodeOrigin:L,getNodes:j}=h.getState();if(!e||!S.current||!C)return;h.setState({userSelectionActive:!0,nodesSelectionActive:!1});const U=Ms(M,S.current),G=C.startX??0,W=C.startY??0,X={...C,x:U.xJ.id),Q=B.map(J=>J.id);if(p.current!==Q.length){p.current=Q.length;const J=du(Y,Q);J.length&&(R==null||R(J))}if(m.current!==H.length){m.current=H.length;const J=du(I,H);J.length&&(D==null||D(J))}h.setState({userSelectionRect:X})},E=M=>{if(M.button!==0)return;const{userSelectionRect:C}=h.getState();!v&&C&&M.target===f.current&&(_==null||_(M)),h.setState({nodesSelectionActive:p.current>0}),b(),i==null||i(M)},A=M=>{v&&(h.setState({nodesSelectionActive:p.current>0}),i==null||i(M)),b()},$=y&&(e||v);return K.jsxs("div",{className:ti(["react-flow__pane",{dragging:g,selection:e}]),onClick:$?void 0:Rb(_,f),onContextMenu:Rb(w,f),onWheel:Rb(x,f),onMouseEnter:$?void 0:l,onMouseDown:$?T:void 0,onMouseMove:$?P:u,onMouseUp:$?E:void 0,onMouseLeave:$?A:c,ref:f,style:sC,children:[d,K.jsx(tie,{})]})});WI.displayName="Pane";const iie=e=>{const t=e.getNodes().filter(n=>n.selected);return{..._I(t,e.nodeOrigin),transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`,userSelectionActive:e.userSelectionActive}};function oie({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){const r=Vn(),{width:i,height:o,x:s,y:a,transformString:l,userSelectionActive:u}=Vt(iie,br),c=jI(),d=k.useRef(null);if(k.useEffect(()=>{var p;n||(p=d.current)==null||p.focus({preventScroll:!0})},[n]),BI({nodeRef:d}),u||!i||!o)return null;const f=e?p=>{const m=r.getState().getNodes().filter(S=>S.selected);e(p,m)}:void 0,h=p=>{Object.prototype.hasOwnProperty.call(Nu,p.key)&&c({x:Nu[p.key].x,y:Nu[p.key].y,isShiftPressed:p.shiftKey})};return K.jsx("div",{className:ti(["react-flow__nodesselection","react-flow__container",t]),style:{transform:l},children:K.jsx("div",{ref:d,className:"react-flow__nodesselection-rect",onContextMenu:f,tabIndex:n?void 0:-1,onKeyDown:n?void 0:h,style:{width:i,height:o,top:a,left:s}})})}var sie=k.memo(oie);const aie=e=>e.nodesSelectionActive,KI=({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:o,onPaneScroll:s,deleteKeyCode:a,onMove:l,onMoveStart:u,onMoveEnd:c,selectionKeyCode:d,selectionOnDrag:f,selectionMode:h,onSelectionStart:p,onSelectionEnd:m,multiSelectionKeyCode:S,panActivationKeyCode:v,zoomActivationKeyCode:y,elementsSelectable:g,zoomOnScroll:b,zoomOnPinch:_,panOnScroll:w,panOnScrollSpeed:x,panOnScrollMode:T,zoomOnDoubleClick:P,panOnDrag:E,defaultViewport:A,translateExtent:$,minZoom:M,maxZoom:C,preventScrolling:O,onSelectionContextMenu:I,noWheelClassName:N,noPanClassName:R,disableKeyboardA11y:D})=>{const L=Vt(aie),j=Nf(d),G=Nf(v)||E,W=j||f&&G!==!0;return Xre({deleteKeyCode:a,multiSelectionKeyCode:S}),K.jsx(Jre,{onMove:l,onMoveStart:u,onMoveEnd:c,onPaneContextMenu:o,elementsSelectable:g,zoomOnScroll:b,zoomOnPinch:_,panOnScroll:w,panOnScrollSpeed:x,panOnScrollMode:T,zoomOnDoubleClick:P,panOnDrag:!j&&G,defaultViewport:A,translateExtent:$,minZoom:M,maxZoom:C,zoomActivationKeyCode:y,preventScrolling:O,noWheelClassName:N,noPanClassName:R,children:K.jsxs(WI,{onSelectionStart:p,onSelectionEnd:m,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:i,onPaneContextMenu:o,onPaneScroll:s,panOnDrag:G,isSelecting:!!W,selectionMode:h,children:[e,L&&K.jsx(sie,{onSelectionContextMenu:I,noPanClassName:R,disableKeyboardA11y:D})]})})};KI.displayName="FlowRenderer";var lie=k.memo(KI);function uie(e){return Vt(k.useCallback(n=>e?wI(n.nodeInternals,{x:0,y:0,width:n.width,height:n.height},n.transform,!0):n.getNodes(),[e]))}const cie=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,updateNodeDimensions:e.updateNodeDimensions,onError:e.onError}),XI=e=>{const{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:i,updateNodeDimensions:o,onError:s}=Vt(cie,br),a=uie(e.onlyRenderVisibleElements),l=k.useRef(),u=k.useMemo(()=>{if(typeof ResizeObserver>"u")return null;const c=new ResizeObserver(d=>{const f=d.map(h=>({id:h.target.getAttribute("data-id"),nodeElement:h.target,forceUpdate:!0}));o(f)});return l.current=c,c},[]);return k.useEffect(()=>()=>{var c;(c=l==null?void 0:l.current)==null||c.disconnect()},[]),K.jsx("div",{className:"react-flow__nodes",style:sC,children:a.map(c=>{var _,w;let d=c.type||"default";e.nodeTypes[d]||(s==null||s("003",qs.error003(d)),d="default");const f=e.nodeTypes[d]||e.nodeTypes.default,h=!!(c.draggable||t&&typeof c.draggable>"u"),p=!!(c.selectable||i&&typeof c.selectable>"u"),m=!!(c.connectable||n&&typeof c.connectable>"u"),S=!!(c.focusable||r&&typeof c.focusable>"u"),v=e.nodeExtent?Jx(c.positionAbsolute,e.nodeExtent):c.positionAbsolute,y=(v==null?void 0:v.x)??0,g=(v==null?void 0:v.y)??0,b=zre({x:y,y:g,width:c.width??0,height:c.height??0,origin:e.nodeOrigin});return K.jsx(f,{id:c.id,className:c.className,style:c.style,type:d,data:c.data,sourcePosition:c.sourcePosition||pe.Bottom,targetPosition:c.targetPosition||pe.Top,hidden:c.hidden,xPos:y,yPos:g,xPosOrigin:b.x,yPosOrigin:b.y,selectNodesOnDrag:e.selectNodesOnDrag,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,selected:!!c.selected,isDraggable:h,isSelectable:p,isConnectable:m,isFocusable:S,resizeObserver:u,dragHandle:c.dragHandle,zIndex:((_=c[on])==null?void 0:_.z)??0,isParent:!!((w=c[on])!=null&&w.isParent),noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,initialized:!!c.width&&!!c.height,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,ariaLabel:c.ariaLabel},c.id)})})};XI.displayName="NodeRenderer";var die=k.memo(XI);const fie=[{level:0,isMaxLevel:!0,edges:[]}];function hie(e,t,n=!1){let r=-1;const i=e.reduce((s,a)=>{var c,d;const l=Kr(a.zIndex);let u=l?a.zIndex:0;if(n){const f=t.get(a.target),h=t.get(a.source),p=a.selected||(f==null?void 0:f.selected)||(h==null?void 0:h.selected),m=Math.max(((c=h==null?void 0:h[on])==null?void 0:c.z)||0,((d=f==null?void 0:f[on])==null?void 0:d.z)||0,1e3);u=(l?a.zIndex:0)+(p?m:0)}return s[u]?s[u].push(a):s[u]=[a],r=u>r?u:r,s},{}),o=Object.entries(i).map(([s,a])=>{const l=+s;return{edges:a,level:l,isMaxLevel:l===r}});return o.length===0?fie:o}function pie(e,t,n){const r=Vt(k.useCallback(i=>e?i.edges.filter(o=>{const s=t.get(o.source),a=t.get(o.target);return(s==null?void 0:s.width)&&(s==null?void 0:s.height)&&(a==null?void 0:a.width)&&(a==null?void 0:a.height)&&$re({sourcePos:s.positionAbsolute||{x:0,y:0},targetPos:a.positionAbsolute||{x:0,y:0},sourceWidth:s.width,sourceHeight:s.height,targetWidth:a.width,targetHeight:a.height,width:i.width,height:i.height,transform:i.transform})}):i.edges,[e,t]));return hie(r,t,n)}const gie=({color:e="none",strokeWidth:t=1})=>K.jsx("polyline",{stroke:e,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:t,fill:"none",points:"-5,-4 0,0 -5,4"}),mie=({color:e="none",strokeWidth:t=1})=>K.jsx("polyline",{stroke:e,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:t,fill:e,points:"-5,-4 0,0 -5,4 -5,-4"}),aE={[Lm.Arrow]:gie,[Lm.ArrowClosed]:mie};function yie(e){const t=Vn();return k.useMemo(()=>{var i,o;return Object.prototype.hasOwnProperty.call(aE,e)?aE[e]:((o=(i=t.getState()).onError)==null||o.call(i,"009",qs.error009(e)),null)},[e])}const vie=({id:e,type:t,color:n,width:r=12.5,height:i=12.5,markerUnits:o="strokeWidth",strokeWidth:s,orient:a="auto-start-reverse"})=>{const l=yie(t);return l?K.jsx("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${i}`,viewBox:"-10 -10 20 20",markerUnits:o,orient:a,refX:"0",refY:"0",children:K.jsx(l,{color:n,strokeWidth:s})}):null},bie=({defaultColor:e,rfId:t})=>n=>{const r=[];return n.edges.reduce((i,o)=>([o.markerStart,o.markerEnd].forEach(s=>{if(s&&typeof s=="object"){const a=n2(s,t);r.includes(a)||(i.push({id:a,color:s.color||e,...s}),r.push(a))}}),i),[]).sort((i,o)=>i.id.localeCompare(o.id))},YI=({defaultColor:e,rfId:t})=>{const n=Vt(k.useCallback(bie({defaultColor:e,rfId:t}),[e,t]),(r,i)=>!(r.length!==i.length||r.some((o,s)=>o.id!==i[s].id)));return K.jsx("defs",{children:n.map(r=>K.jsx(vie,{id:r.id,type:r.type,color:r.color,width:r.width,height:r.height,markerUnits:r.markerUnits,strokeWidth:r.strokeWidth,orient:r.orient},r.id))})};YI.displayName="MarkerDefinitions";var Sie=k.memo(YI);const _ie=e=>({nodesConnectable:e.nodesConnectable,edgesFocusable:e.edgesFocusable,edgesUpdatable:e.edgesUpdatable,elementsSelectable:e.elementsSelectable,width:e.width,height:e.height,connectionMode:e.connectionMode,nodeInternals:e.nodeInternals,onError:e.onError}),QI=({defaultMarkerColor:e,onlyRenderVisibleElements:t,elevateEdgesOnSelect:n,rfId:r,edgeTypes:i,noPanClassName:o,onEdgeUpdate:s,onEdgeContextMenu:a,onEdgeMouseEnter:l,onEdgeMouseMove:u,onEdgeMouseLeave:c,onEdgeClick:d,edgeUpdaterRadius:f,onEdgeDoubleClick:h,onEdgeUpdateStart:p,onEdgeUpdateEnd:m,children:S})=>{const{edgesFocusable:v,edgesUpdatable:y,elementsSelectable:g,width:b,height:_,connectionMode:w,nodeInternals:x,onError:T}=Vt(_ie,br),P=pie(t,x,n);return b?K.jsxs(K.Fragment,{children:[P.map(({level:E,edges:A,isMaxLevel:$})=>K.jsxs("svg",{style:{zIndex:E},width:b,height:_,className:"react-flow__edges react-flow__container",children:[$&&K.jsx(Sie,{defaultColor:e,rfId:r}),K.jsx("g",{children:A.map(M=>{const[C,O,I]=eE(x.get(M.source)),[N,R,D]=eE(x.get(M.target));if(!I||!D)return null;let L=M.type||"default";i[L]||(T==null||T("011",qs.error011(L)),L="default");const j=i[L]||i.default,U=w===nl.Strict?R.target:(R.target??[]).concat(R.source??[]),G=JT(O.source,M.sourceHandle),W=JT(U,M.targetHandle),X=(G==null?void 0:G.position)||pe.Bottom,Y=(W==null?void 0:W.position)||pe.Top,B=!!(M.focusable||v&&typeof M.focusable>"u"),H=typeof s<"u"&&(M.updatable||y&&typeof M.updatable>"u");if(!G||!W)return T==null||T("008",qs.error008(G,M)),null;const{sourceX:Q,sourceY:J,targetX:ne,targetY:te}=Lre(C,G,X,N,W,Y);return K.jsx(j,{id:M.id,className:ti([M.className,o]),type:L,data:M.data,selected:!!M.selected,animated:!!M.animated,hidden:!!M.hidden,label:M.label,labelStyle:M.labelStyle,labelShowBg:M.labelShowBg,labelBgStyle:M.labelBgStyle,labelBgPadding:M.labelBgPadding,labelBgBorderRadius:M.labelBgBorderRadius,style:M.style,source:M.source,target:M.target,sourceHandleId:M.sourceHandle,targetHandleId:M.targetHandle,markerEnd:M.markerEnd,markerStart:M.markerStart,sourceX:Q,sourceY:J,targetX:ne,targetY:te,sourcePosition:X,targetPosition:Y,elementsSelectable:g,onEdgeUpdate:s,onContextMenu:a,onMouseEnter:l,onMouseMove:u,onMouseLeave:c,onClick:d,edgeUpdaterRadius:f,onEdgeDoubleClick:h,onEdgeUpdateStart:p,onEdgeUpdateEnd:m,rfId:r,ariaLabel:M.ariaLabel,isFocusable:B,isUpdatable:H,pathOptions:"pathOptions"in M?M.pathOptions:void 0,interactionWidth:M.interactionWidth},M.id)})})]},E)),S]}):null};QI.displayName="EdgeRenderer";var wie=k.memo(QI);const xie=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function Cie({children:e}){const t=Vt(xie);return K.jsx("div",{className:"react-flow__viewport react-flow__container",style:{transform:t},children:e})}function Tie(e){const t=GI(),n=k.useRef(!1);k.useEffect(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}const Eie={[pe.Left]:pe.Right,[pe.Right]:pe.Left,[pe.Top]:pe.Bottom,[pe.Bottom]:pe.Top},ZI=({nodeId:e,handleType:t,style:n,type:r=ys.Bezier,CustomComponent:i,connectionStatus:o})=>{var w,x,T;const{fromNode:s,handleId:a,toX:l,toY:u,connectionMode:c}=Vt(k.useCallback(P=>({fromNode:P.nodeInternals.get(e),handleId:P.connectionHandleId,toX:(P.connectionPosition.x-P.transform[0])/P.transform[2],toY:(P.connectionPosition.y-P.transform[1])/P.transform[2],connectionMode:P.connectionMode}),[e]),br),d=(w=s==null?void 0:s[on])==null?void 0:w.handleBounds;let f=d==null?void 0:d[t];if(c===nl.Loose&&(f=f||(d==null?void 0:d[t==="source"?"target":"source"])),!s||!f)return null;const h=a?f.find(P=>P.id===a):f[0],p=h?h.x+h.width/2:(s.width??0)/2,m=h?h.y+h.height/2:s.height??0,S=(((x=s.positionAbsolute)==null?void 0:x.x)??0)+p,v=(((T=s.positionAbsolute)==null?void 0:T.y)??0)+m,y=h==null?void 0:h.position,g=y?Eie[y]:null;if(!y||!g)return null;if(i)return K.jsx(i,{connectionLineType:r,connectionLineStyle:n,fromNode:s,fromHandle:h,fromX:S,fromY:v,toX:l,toY:u,fromPosition:y,toPosition:g,connectionStatus:o});let b="";const _={sourceX:S,sourceY:v,sourcePosition:y,targetX:l,targetY:u,targetPosition:g};return r===ys.Bezier?[b]=vI(_):r===ys.Step?[b]=t2({..._,borderRadius:0}):r===ys.SmoothStep?[b]=t2(_):r===ys.SimpleBezier?[b]=yI(_):b=`M${S},${v} ${l},${u}`,K.jsx("path",{d:b,fill:"none",className:"react-flow__connection-path",style:n})};ZI.displayName="ConnectionLine";const Pie=e=>({nodeId:e.connectionNodeId,handleType:e.connectionHandleType,nodesConnectable:e.nodesConnectable,connectionStatus:e.connectionStatus,width:e.width,height:e.height});function Aie({containerStyle:e,style:t,type:n,component:r}){const{nodeId:i,handleType:o,nodesConnectable:s,width:a,height:l,connectionStatus:u}=Vt(Pie,br);return!(i&&o&&a&&s)?null:K.jsx("svg",{style:e,width:a,height:l,className:"react-flow__edges react-flow__connectionline react-flow__container",children:K.jsx("g",{className:ti(["react-flow__connection",u]),children:K.jsx(ZI,{nodeId:i,handleType:o,style:t,type:n,CustomComponent:r,connectionStatus:u})})})}const JI=({nodeTypes:e,edgeTypes:t,onMove:n,onMoveStart:r,onMoveEnd:i,onInit:o,onNodeClick:s,onEdgeClick:a,onNodeDoubleClick:l,onEdgeDoubleClick:u,onNodeMouseEnter:c,onNodeMouseMove:d,onNodeMouseLeave:f,onNodeContextMenu:h,onSelectionContextMenu:p,onSelectionStart:m,onSelectionEnd:S,connectionLineType:v,connectionLineStyle:y,connectionLineComponent:g,connectionLineContainerStyle:b,selectionKeyCode:_,selectionOnDrag:w,selectionMode:x,multiSelectionKeyCode:T,panActivationKeyCode:P,zoomActivationKeyCode:E,deleteKeyCode:A,onlyRenderVisibleElements:$,elementsSelectable:M,selectNodesOnDrag:C,defaultViewport:O,translateExtent:I,minZoom:N,maxZoom:R,preventScrolling:D,defaultMarkerColor:L,zoomOnScroll:j,zoomOnPinch:U,panOnScroll:G,panOnScrollSpeed:W,panOnScrollMode:X,zoomOnDoubleClick:Y,panOnDrag:B,onPaneClick:H,onPaneMouseEnter:Q,onPaneMouseMove:J,onPaneMouseLeave:ne,onPaneScroll:te,onPaneContextMenu:xe,onEdgeUpdate:ve,onEdgeContextMenu:ce,onEdgeMouseEnter:Ne,onEdgeMouseMove:se,onEdgeMouseLeave:gt,edgeUpdaterRadius:vn,onEdgeUpdateStart:It,onEdgeUpdateEnd:ut,noDragClassName:Je,noWheelClassName:Gt,noPanClassName:sr,elevateEdgesOnSelect:ni,disableKeyboardA11y:Lr,nodeOrigin:Rn,nodeExtent:bn,rfId:Un})=>(Tie(o),K.jsx(lie,{onPaneClick:H,onPaneMouseEnter:Q,onPaneMouseMove:J,onPaneMouseLeave:ne,onPaneContextMenu:xe,onPaneScroll:te,deleteKeyCode:A,selectionKeyCode:_,selectionOnDrag:w,selectionMode:x,onSelectionStart:m,onSelectionEnd:S,multiSelectionKeyCode:T,panActivationKeyCode:P,zoomActivationKeyCode:E,elementsSelectable:M,onMove:n,onMoveStart:r,onMoveEnd:i,zoomOnScroll:j,zoomOnPinch:U,zoomOnDoubleClick:Y,panOnScroll:G,panOnScrollSpeed:W,panOnScrollMode:X,panOnDrag:B,defaultViewport:O,translateExtent:I,minZoom:N,maxZoom:R,onSelectionContextMenu:p,preventScrolling:D,noDragClassName:Je,noWheelClassName:Gt,noPanClassName:sr,disableKeyboardA11y:Lr,children:K.jsxs(Cie,{children:[K.jsx(wie,{edgeTypes:t,onEdgeClick:a,onEdgeDoubleClick:u,onEdgeUpdate:ve,onlyRenderVisibleElements:$,onEdgeContextMenu:ce,onEdgeMouseEnter:Ne,onEdgeMouseMove:se,onEdgeMouseLeave:gt,onEdgeUpdateStart:It,onEdgeUpdateEnd:ut,edgeUpdaterRadius:vn,defaultMarkerColor:L,noPanClassName:sr,elevateEdgesOnSelect:!!ni,disableKeyboardA11y:Lr,rfId:Un,children:K.jsx(Aie,{style:y,type:v,component:g,containerStyle:b})}),K.jsx("div",{className:"react-flow__edgelabel-renderer"}),K.jsx(die,{nodeTypes:e,onNodeClick:s,onNodeDoubleClick:l,onNodeMouseEnter:c,onNodeMouseMove:d,onNodeMouseLeave:f,onNodeContextMenu:h,selectNodesOnDrag:C,onlyRenderVisibleElements:$,noPanClassName:sr,noDragClassName:Je,disableKeyboardA11y:Lr,nodeOrigin:Rn,nodeExtent:bn,rfId:Un})]})}));JI.displayName="GraphView";var kie=k.memo(JI);const o2=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],rs={rfId:"1",width:0,height:0,transform:[0,0,1],nodeInternals:new Map,edges:[],onNodesChange:null,onEdgesChange:null,hasDefaultNodes:!1,hasDefaultEdges:!1,d3Zoom:null,d3Selection:null,d3ZoomHandler:void 0,minZoom:.5,maxZoom:2,translateExtent:o2,nodeExtent:o2,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionNodeId:null,connectionHandleId:null,connectionHandleType:"source",connectionPosition:{x:0,y:0},connectionStatus:null,connectionMode:nl.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:[0,0],snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesUpdatable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,fitViewOnInit:!1,fitViewOnInitDone:!1,fitViewOnInitOptions:void 0,multiSelectionActive:!1,connectionStartHandle:null,connectionEndHandle:null,connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,connectionRadius:20,onError:rre,isValidConnection:void 0},Oie=()=>gJ((e,t)=>({...rs,setNodes:n=>{const{nodeInternals:r,nodeOrigin:i,elevateNodesOnSelect:o}=t();e({nodeInternals:kb(n,r,i,o)})},getNodes:()=>Array.from(t().nodeInternals.values()),setEdges:n=>{const{defaultEdgeOptions:r={}}=t();e({edges:n.map(i=>({...r,...i}))})},setDefaultNodesAndEdges:(n,r)=>{const i=typeof n<"u",o=typeof r<"u",s=i?kb(n,new Map,t().nodeOrigin,t().elevateNodesOnSelect):new Map;e({nodeInternals:s,edges:o?r:[],hasDefaultNodes:i,hasDefaultEdges:o})},updateNodeDimensions:n=>{const{onNodesChange:r,nodeInternals:i,fitViewOnInit:o,fitViewOnInitDone:s,fitViewOnInitOptions:a,domNode:l,nodeOrigin:u}=t(),c=l==null?void 0:l.querySelector(".react-flow__viewport");if(!c)return;const d=window.getComputedStyle(c),{m22:f}=new window.DOMMatrixReadOnly(d.transform),h=n.reduce((m,S)=>{const v=i.get(S.id);if(v){const y=Zx(S.nodeElement);!!(y.width&&y.height&&(v.width!==y.width||v.height!==y.height||S.forceUpdate))&&(i.set(v.id,{...v,[on]:{...v[on],handleBounds:{source:nE(".source",S.nodeElement,f,u),target:nE(".target",S.nodeElement,f,u)}},...y}),m.push({id:v.id,type:"dimensions",dimensions:y}))}return m},[]);zI(i,u);const p=s||o&&!s&&UI(t,{initial:!0,...a});e({nodeInternals:new Map(i),fitViewOnInitDone:p}),(h==null?void 0:h.length)>0&&(r==null||r(h))},updateNodePositions:(n,r=!0,i=!1)=>{const{triggerNodeChanges:o}=t(),s=n.map(a=>{const l={id:a.id,type:"position",dragging:i};return r&&(l.positionAbsolute=a.positionAbsolute,l.position=a.position),l});o(s)},triggerNodeChanges:n=>{const{onNodesChange:r,nodeInternals:i,hasDefaultNodes:o,nodeOrigin:s,getNodes:a,elevateNodesOnSelect:l}=t();if(n!=null&&n.length){if(o){const u=qI(n,a()),c=kb(u,i,s,l);e({nodeInternals:c})}r==null||r(n)}},addSelectedNodes:n=>{const{multiSelectionActive:r,edges:i,getNodes:o}=t();let s,a=null;r?s=n.map(l=>ds(l,!0)):(s=du(o(),n),a=du(i,[])),kp({changedNodes:s,changedEdges:a,get:t,set:e})},addSelectedEdges:n=>{const{multiSelectionActive:r,edges:i,getNodes:o}=t();let s,a=null;r?s=n.map(l=>ds(l,!0)):(s=du(i,n),a=du(o(),[])),kp({changedNodes:a,changedEdges:s,get:t,set:e})},unselectNodesAndEdges:({nodes:n,edges:r}={})=>{const{edges:i,getNodes:o}=t(),s=n||o(),a=r||i,l=s.map(c=>(c.selected=!1,ds(c.id,!1))),u=a.map(c=>ds(c.id,!1));kp({changedNodes:l,changedEdges:u,get:t,set:e})},setMinZoom:n=>{const{d3Zoom:r,maxZoom:i}=t();r==null||r.scaleExtent([n,i]),e({minZoom:n})},setMaxZoom:n=>{const{d3Zoom:r,minZoom:i}=t();r==null||r.scaleExtent([i,n]),e({maxZoom:n})},setTranslateExtent:n=>{var r;(r=t().d3Zoom)==null||r.translateExtent(n),e({translateExtent:n})},resetSelectedElements:()=>{const{edges:n,getNodes:r}=t(),o=r().filter(a=>a.selected).map(a=>ds(a.id,!1)),s=n.filter(a=>a.selected).map(a=>ds(a.id,!1));kp({changedNodes:o,changedEdges:s,get:t,set:e})},setNodeExtent:n=>{const{nodeInternals:r}=t();r.forEach(i=>{i.positionAbsolute=Jx(i.position,n)}),e({nodeExtent:n,nodeInternals:new Map(r)})},panBy:n=>{const{transform:r,width:i,height:o,d3Zoom:s,d3Selection:a,translateExtent:l}=t();if(!s||!a||!n.x&&!n.y)return!1;const u=Is.translate(r[0]+n.x,r[1]+n.y).scale(r[2]),c=[[0,0],[i,o]],d=s==null?void 0:s.constrain()(u,c,l);return s.transform(a,d),r[0]!==d.x||r[1]!==d.y||r[2]!==d.k},cancelConnection:()=>e({connectionNodeId:rs.connectionNodeId,connectionHandleId:rs.connectionHandleId,connectionHandleType:rs.connectionHandleType,connectionStatus:rs.connectionStatus,connectionStartHandle:rs.connectionStartHandle,connectionEndHandle:rs.connectionEndHandle}),reset:()=>e({...rs})})),eM=({children:e})=>{const t=k.useRef(null);return t.current||(t.current=Oie()),K.jsx(Yne,{value:t.current,children:e})};eM.displayName="ReactFlowProvider";const tM=({children:e})=>k.useContext(R0)?K.jsx(K.Fragment,{children:e}):K.jsx(eM,{children:e});tM.displayName="ReactFlowWrapper";function lE(e,t){return k.useRef(null),k.useMemo(()=>t(e),[e])}const Rie={input:RI,default:r2,output:MI,group:oC},Iie={default:$m,straight:nC,step:tC,smoothstep:I0,simplebezier:eC},Mie=[0,0],Nie=[15,15],Die={x:0,y:0,zoom:1},Lie={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},$ie=k.forwardRef(({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:i,nodeTypes:o=Rie,edgeTypes:s=Iie,onNodeClick:a,onEdgeClick:l,onInit:u,onMove:c,onMoveStart:d,onMoveEnd:f,onConnect:h,onConnectStart:p,onConnectEnd:m,onClickConnectStart:S,onClickConnectEnd:v,onNodeMouseEnter:y,onNodeMouseMove:g,onNodeMouseLeave:b,onNodeContextMenu:_,onNodeDoubleClick:w,onNodeDragStart:x,onNodeDrag:T,onNodeDragStop:P,onNodesDelete:E,onEdgesDelete:A,onSelectionChange:$,onSelectionDragStart:M,onSelectionDrag:C,onSelectionDragStop:O,onSelectionContextMenu:I,onSelectionStart:N,onSelectionEnd:R,connectionMode:D=nl.Strict,connectionLineType:L=ys.Bezier,connectionLineStyle:j,connectionLineComponent:U,connectionLineContainerStyle:G,deleteKeyCode:W="Backspace",selectionKeyCode:X="Shift",selectionOnDrag:Y=!1,selectionMode:B=Mf.Full,panActivationKeyCode:H="Space",multiSelectionKeyCode:Q="Meta",zoomActivationKeyCode:J="Meta",snapToGrid:ne=!1,snapGrid:te=Nie,onlyRenderVisibleElements:xe=!1,selectNodesOnDrag:ve=!0,nodesDraggable:ce,nodesConnectable:Ne,nodesFocusable:se,nodeOrigin:gt=Mie,edgesFocusable:vn,edgesUpdatable:It,elementsSelectable:ut,defaultViewport:Je=Die,minZoom:Gt=.5,maxZoom:sr=2,translateExtent:ni=o2,preventScrolling:Lr=!0,nodeExtent:Rn,defaultMarkerColor:bn="#b1b1b7",zoomOnScroll:Un=!0,zoomOnPinch:Ht=!0,panOnScroll:xt=!1,panOnScrollSpeed:wr=.5,panOnScrollMode:$r=Iu.Free,zoomOnDoubleClick:ri=!0,panOnDrag:uo=!0,onPaneClick:Sn,onPaneMouseEnter:ii,onPaneMouseMove:ca,onPaneMouseLeave:ki,onPaneScroll:da,onPaneContextMenu:Ct,children:et,onEdgeUpdate:_n,onEdgeContextMenu:ln,onEdgeDoubleClick:In,onEdgeMouseEnter:Gn,onEdgeMouseMove:ar,onEdgeMouseLeave:Oi,onEdgeUpdateStart:Hn,onEdgeUpdateEnd:wn,edgeUpdaterRadius:co=10,onNodesChange:Zo,onEdgesChange:Jo,noDragClassName:Al="nodrag",noWheelClassName:fo="nowheel",noPanClassName:qn="nopan",fitView:fa=!1,fitViewOptions:h1,connectOnClick:p1=!0,attributionPosition:g1,proOptions:m1,defaultEdgeOptions:es,elevateNodesOnSelect:y1=!0,elevateEdgesOnSelect:v1=!1,disableKeyboardA11y:Hh=!1,autoPanOnConnect:b1=!0,autoPanOnNodeDrag:S1=!0,connectionRadius:_1=20,isValidConnection:Ac,onError:w1,style:kl,id:Ol,...x1},Rl)=>{const qh=lE(o,Vre),C1=lE(s,Dre),kc=Ol||"1";return K.jsx("div",{...x1,style:{...kl,...Lie},ref:Rl,className:ti(["react-flow",i]),"data-testid":"rf__wrapper",id:Ol,children:K.jsxs(tM,{children:[K.jsx(kie,{onInit:u,onMove:c,onMoveStart:d,onMoveEnd:f,onNodeClick:a,onEdgeClick:l,onNodeMouseEnter:y,onNodeMouseMove:g,onNodeMouseLeave:b,onNodeContextMenu:_,onNodeDoubleClick:w,nodeTypes:qh,edgeTypes:C1,connectionLineType:L,connectionLineStyle:j,connectionLineComponent:U,connectionLineContainerStyle:G,selectionKeyCode:X,selectionOnDrag:Y,selectionMode:B,deleteKeyCode:W,multiSelectionKeyCode:Q,panActivationKeyCode:H,zoomActivationKeyCode:J,onlyRenderVisibleElements:xe,selectNodesOnDrag:ve,defaultViewport:Je,translateExtent:ni,minZoom:Gt,maxZoom:sr,preventScrolling:Lr,zoomOnScroll:Un,zoomOnPinch:Ht,zoomOnDoubleClick:ri,panOnScroll:xt,panOnScrollSpeed:wr,panOnScrollMode:$r,panOnDrag:uo,onPaneClick:Sn,onPaneMouseEnter:ii,onPaneMouseMove:ca,onPaneMouseLeave:ki,onPaneScroll:da,onPaneContextMenu:Ct,onSelectionContextMenu:I,onSelectionStart:N,onSelectionEnd:R,onEdgeUpdate:_n,onEdgeContextMenu:ln,onEdgeDoubleClick:In,onEdgeMouseEnter:Gn,onEdgeMouseMove:ar,onEdgeMouseLeave:Oi,onEdgeUpdateStart:Hn,onEdgeUpdateEnd:wn,edgeUpdaterRadius:co,defaultMarkerColor:bn,noDragClassName:Al,noWheelClassName:fo,noPanClassName:qn,elevateEdgesOnSelect:v1,rfId:kc,disableKeyboardA11y:Hh,nodeOrigin:gt,nodeExtent:Rn}),K.jsx(Ere,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:h,onConnectStart:p,onConnectEnd:m,onClickConnectStart:S,onClickConnectEnd:v,nodesDraggable:ce,nodesConnectable:Ne,nodesFocusable:se,edgesFocusable:vn,edgesUpdatable:It,elementsSelectable:ut,elevateNodesOnSelect:y1,minZoom:Gt,maxZoom:sr,nodeExtent:Rn,onNodesChange:Zo,onEdgesChange:Jo,snapToGrid:ne,snapGrid:te,connectionMode:D,translateExtent:ni,connectOnClick:p1,defaultEdgeOptions:es,fitView:fa,fitViewOptions:h1,onNodesDelete:E,onEdgesDelete:A,onNodeDragStart:x,onNodeDrag:T,onNodeDragStop:P,onSelectionDrag:C,onSelectionDragStart:M,onSelectionDragStop:O,noPanClassName:qn,nodeOrigin:gt,rfId:kc,autoPanOnConnect:b1,autoPanOnNodeDrag:S1,onError:w1,connectionRadius:_1,isValidConnection:Ac}),K.jsx(Cre,{onSelectionChange:$}),et,K.jsx(Jne,{proOptions:m1,position:g1}),K.jsx(Rre,{rfId:kc,disableKeyboardA11y:Hh})]})})});$ie.displayName="ReactFlow";var nM={},M0={},N0={};Object.defineProperty(N0,"__esModule",{value:!0});N0.createLogMethods=void 0;var Fie=function(){return{debug:console.debug.bind(console),error:console.error.bind(console),fatal:console.error.bind(console),info:console.info.bind(console),trace:console.debug.bind(console),warn:console.warn.bind(console)}};N0.createLogMethods=Fie;var aC={},D0={};Object.defineProperty(D0,"__esModule",{value:!0});D0.boolean=void 0;const Bie=function(e){switch(Object.prototype.toString.call(e)){case"[object String]":return["true","t","yes","y","on","1"].includes(e.trim().toLowerCase());case"[object Number]":return e.valueOf()===1;case"[object Boolean]":return e.valueOf();default:return!1}};D0.boolean=Bie;var L0={};Object.defineProperty(L0,"__esModule",{value:!0});L0.isBooleanable=void 0;const jie=function(e){switch(Object.prototype.toString.call(e)){case"[object String]":return["true","t","yes","y","on","1","false","f","no","n","off","0"].includes(e.trim().toLowerCase());case"[object Number]":return[0,1].includes(e.valueOf());case"[object Boolean]":return!0;default:return!1}};L0.isBooleanable=jie;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.isBooleanable=e.boolean=void 0;const t=D0;Object.defineProperty(e,"boolean",{enumerable:!0,get:function(){return t.boolean}});const n=L0;Object.defineProperty(e,"isBooleanable",{enumerable:!0,get:function(){return n.isBooleanable}})})(aC);var uE=Object.prototype.toString,rM=function(t){var n=uE.call(t),r=n==="[object Arguments]";return r||(r=n!=="[object Array]"&&t!==null&&typeof t=="object"&&typeof t.length=="number"&&t.length>=0&&uE.call(t.callee)==="[object Function]"),r},Ib,cE;function Vie(){if(cE)return Ib;cE=1;var e;if(!Object.keys){var t=Object.prototype.hasOwnProperty,n=Object.prototype.toString,r=rM,i=Object.prototype.propertyIsEnumerable,o=!i.call({toString:null},"toString"),s=i.call(function(){},"prototype"),a=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],l=function(f){var h=f.constructor;return h&&h.prototype===f},u={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},c=function(){if(typeof window>"u")return!1;for(var f in window)try{if(!u["$"+f]&&t.call(window,f)&&window[f]!==null&&typeof window[f]=="object")try{l(window[f])}catch{return!0}}catch{return!0}return!1}(),d=function(f){if(typeof window>"u"||!c)return l(f);try{return l(f)}catch{return!1}};e=function(h){var p=h!==null&&typeof h=="object",m=n.call(h)==="[object Function]",S=r(h),v=p&&n.call(h)==="[object String]",y=[];if(!p&&!m&&!S)throw new TypeError("Object.keys called on a non-object");var g=s&&m;if(v&&h.length>0&&!t.call(h,0))for(var b=0;b0)for(var _=0;_"u"||!cn?Oe:cn(Uint8Array),Ua={"%AggregateError%":typeof AggregateError>"u"?Oe:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?Oe:ArrayBuffer,"%ArrayIteratorPrototype%":Bl&&cn?cn([][Symbol.iterator]()):Oe,"%AsyncFromSyncIteratorPrototype%":Oe,"%AsyncFunction%":Yl,"%AsyncGenerator%":Yl,"%AsyncGeneratorFunction%":Yl,"%AsyncIteratorPrototype%":Yl,"%Atomics%":typeof Atomics>"u"?Oe:Atomics,"%BigInt%":typeof BigInt>"u"?Oe:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?Oe:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?Oe:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?Oe:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":typeof Float32Array>"u"?Oe:Float32Array,"%Float64Array%":typeof Float64Array>"u"?Oe:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?Oe:FinalizationRegistry,"%Function%":oM,"%GeneratorFunction%":Yl,"%Int8Array%":typeof Int8Array>"u"?Oe:Int8Array,"%Int16Array%":typeof Int16Array>"u"?Oe:Int16Array,"%Int32Array%":typeof Int32Array>"u"?Oe:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Bl&&cn?cn(cn([][Symbol.iterator]())):Oe,"%JSON%":typeof JSON=="object"?JSON:Oe,"%Map%":typeof Map>"u"?Oe:Map,"%MapIteratorPrototype%":typeof Map>"u"||!Bl||!cn?Oe:cn(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?Oe:Promise,"%Proxy%":typeof Proxy>"u"?Oe:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":typeof Reflect>"u"?Oe:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?Oe:Set,"%SetIteratorPrototype%":typeof Set>"u"||!Bl||!cn?Oe:cn(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?Oe:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Bl&&cn?cn(""[Symbol.iterator]()):Oe,"%Symbol%":Bl?Symbol:Oe,"%SyntaxError%":ic,"%ThrowTypeError%":roe,"%TypedArray%":ooe,"%TypeError%":Du,"%Uint8Array%":typeof Uint8Array>"u"?Oe:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?Oe:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?Oe:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?Oe:Uint32Array,"%URIError%":URIError,"%WeakMap%":typeof WeakMap>"u"?Oe:WeakMap,"%WeakRef%":typeof WeakRef>"u"?Oe:WeakRef,"%WeakSet%":typeof WeakSet>"u"?Oe:WeakSet};if(cn)try{null.error}catch(e){var soe=cn(cn(e));Ua["%Error.prototype%"]=soe}var aoe=function e(t){var n;if(t==="%AsyncFunction%")n=Nb("async function () {}");else if(t==="%GeneratorFunction%")n=Nb("function* () {}");else if(t==="%AsyncGeneratorFunction%")n=Nb("async function* () {}");else if(t==="%AsyncGenerator%"){var r=e("%AsyncGeneratorFunction%");r&&(n=r.prototype)}else if(t==="%AsyncIteratorPrototype%"){var i=e("%AsyncGenerator%");i&&cn&&(n=cn(i.prototype))}return Ua[t]=n,n},gE={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},_h=iM,Bm=noe,loe=_h.call(Function.call,Array.prototype.concat),uoe=_h.call(Function.apply,Array.prototype.splice),mE=_h.call(Function.call,String.prototype.replace),jm=_h.call(Function.call,String.prototype.slice),coe=_h.call(Function.call,RegExp.prototype.exec),doe=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,foe=/\\(\\)?/g,hoe=function(t){var n=jm(t,0,1),r=jm(t,-1);if(n==="%"&&r!=="%")throw new ic("invalid intrinsic syntax, expected closing `%`");if(r==="%"&&n!=="%")throw new ic("invalid intrinsic syntax, expected opening `%`");var i=[];return mE(t,doe,function(o,s,a,l){i[i.length]=a?mE(l,foe,"$1"):s||o}),i},poe=function(t,n){var r=t,i;if(Bm(gE,r)&&(i=gE[r],r="%"+i[0]+"%"),Bm(Ua,r)){var o=Ua[r];if(o===Yl&&(o=aoe(r)),typeof o>"u"&&!n)throw new Du("intrinsic "+t+" exists, but is not available. Please file an issue!");return{alias:i,name:r,value:o}}throw new ic("intrinsic "+t+" does not exist!")},goe=function(t,n){if(typeof t!="string"||t.length===0)throw new Du("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof n!="boolean")throw new Du('"allowMissing" argument must be a boolean');if(coe(/^%?[^%]*%?$/,t)===null)throw new ic("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=hoe(t),i=r.length>0?r[0]:"",o=poe("%"+i+"%",n),s=o.name,a=o.value,l=!1,u=o.alias;u&&(i=u[0],uoe(r,loe([0,1],u)));for(var c=1,d=!0;c=r.length){var m=za(a,f);d=!!m,d&&"get"in m&&!("originalValue"in m.get)?a=m.get:a=a[f]}else d=Bm(a,f),a=a[f];d&&!l&&(Ua[s]=a)}}return a},moe=goe,s2=moe("%Object.defineProperty%",!0),a2=function(){if(s2)try{return s2({},"a",{value:1}),!0}catch{return!1}return!1};a2.hasArrayLengthDefineBug=function(){if(!a2())return null;try{return s2([],"length",{value:1}).length!==1}catch{return!0}};var yoe=a2,voe=Gie,boe=typeof Symbol=="function"&&typeof Symbol("foo")=="symbol",Soe=Object.prototype.toString,_oe=Array.prototype.concat,sM=Object.defineProperty,woe=function(e){return typeof e=="function"&&Soe.call(e)==="[object Function]"},xoe=yoe(),aM=sM&&xoe,Coe=function(e,t,n,r){if(t in e){if(r===!0){if(e[t]===n)return}else if(!woe(r)||!r())return}aM?sM(e,t,{configurable:!0,enumerable:!1,value:n,writable:!0}):e[t]=n},lM=function(e,t){var n=arguments.length>2?arguments[2]:{},r=voe(t);boe&&(r=_oe.call(r,Object.getOwnPropertySymbols(t)));for(var i=0;i":return t>e;case":<":return t=":return t>=e;case":<=":return t<=e;default:throw new Error("Unimplemented comparison operator: ".concat(n))}};j0.testComparisonRange=Hoe;var V0={};Object.defineProperty(V0,"__esModule",{value:!0});V0.testRange=void 0;var qoe=function(e,t){return typeof e=="number"?!(et.max||e===t.max&&!t.maxInclusive):!1};V0.testRange=qoe;(function(e){var t=Ee&&Ee.__assign||function(){return t=Object.assign||function(c){for(var d,f=1,h=arguments.length;f0?{path:l.path,query:new RegExp("("+l.keywords.map(function(u){return(0,Xoe.escapeRegexString)(u.trim())}).join("|")+")")}:{path:l.path}})};z0.highlight=Qoe;var U0={},gM={exports:{}};(function(e){(function(t,n){e.exports?e.exports=n():t.nearley=n()})(Ee,function(){function t(u,c,d){return this.id=++t.highestId,this.name=u,this.symbols=c,this.postprocess=d,this}t.highestId=0,t.prototype.toString=function(u){var c=typeof u>"u"?this.symbols.map(l).join(" "):this.symbols.slice(0,u).map(l).join(" ")+" ● "+this.symbols.slice(u).map(l).join(" ");return this.name+" → "+c};function n(u,c,d,f){this.rule=u,this.dot=c,this.reference=d,this.data=[],this.wantedBy=f,this.isComplete=this.dot===u.symbols.length}n.prototype.toString=function(){return"{"+this.rule.toString(this.dot)+"}, from: "+(this.reference||0)},n.prototype.nextState=function(u){var c=new n(this.rule,this.dot+1,this.reference,this.wantedBy);return c.left=this,c.right=u,c.isComplete&&(c.data=c.build(),c.right=void 0),c},n.prototype.build=function(){var u=[],c=this;do u.push(c.right.data),c=c.left;while(c.left);return u.reverse(),u},n.prototype.finish=function(){this.rule.postprocess&&(this.data=this.rule.postprocess(this.data,this.reference,s.fail))};function r(u,c){this.grammar=u,this.index=c,this.states=[],this.wants={},this.scannable=[],this.completed={}}r.prototype.process=function(u){for(var c=this.states,d=this.wants,f=this.completed,h=0;h0&&c.push(" ^ "+f+" more lines identical to this"),f=0,c.push(" "+m)),d=m}},s.prototype.getSymbolDisplay=function(u){return a(u)},s.prototype.buildFirstStateStack=function(u,c){if(c.indexOf(u)!==-1)return null;if(u.wantedBy.length===0)return[u];var d=u.wantedBy[0],f=[u].concat(c),h=this.buildFirstStateStack(d,f);return h===null?null:[u].concat(h)},s.prototype.save=function(){var u=this.table[this.current];return u.lexerState=this.lexerState,u},s.prototype.restore=function(u){var c=u.index;this.current=c,this.table[c]=u,this.table.splice(c+1),this.lexerState=u.lexerState,this.results=this.finish()},s.prototype.rewind=function(u){if(!this.options.keepHistory)throw new Error("set option `keepHistory` to enable rewinding");this.restore(this.table[u])},s.prototype.finish=function(){var u=[],c=this.grammar.start,d=this.table[this.table.length-1];return d.states.forEach(function(f){f.rule.name===c&&f.dot===f.rule.symbols.length&&f.reference===0&&f.data!==s.fail&&u.push(f)}),u.map(function(f){return f.data})};function a(u){var c=typeof u;if(c==="string")return u;if(c==="object"){if(u.literal)return JSON.stringify(u.literal);if(u instanceof RegExp)return"character matching "+u;if(u.type)return u.type+" token";if(u.test)return"token matching "+String(u.test);throw new Error("Unknown symbol type: "+u)}}function l(u){var c=typeof u;if(c==="string")return u;if(c==="object"){if(u.literal)return JSON.stringify(u.literal);if(u instanceof RegExp)return u.toString();if(u.type)return"%"+u.type;if(u.test)return"<"+String(u.test)+">";throw new Error("Unknown symbol type: "+u)}}return{Parser:s,Grammar:i,Rule:t}})})(gM);var Zoe=gM.exports,rl={},mM={},na={};na.__esModule=void 0;na.__esModule=!0;var Joe=typeof Object.setPrototypeOf=="function",ese=typeof Object.getPrototypeOf=="function",tse=typeof Object.defineProperty=="function",nse=typeof Object.create=="function",rse=typeof Object.prototype.hasOwnProperty=="function",ise=function(t,n){Joe?Object.setPrototypeOf(t,n):t.__proto__=n};na.setPrototypeOf=ise;var ose=function(t){return ese?Object.getPrototypeOf(t):t.__proto__||t.prototype};na.getPrototypeOf=ose;var yE=!1,sse=function e(t,n,r){if(tse&&!yE)try{Object.defineProperty(t,n,r)}catch{yE=!0,e(t,n,r)}else t[n]=r.value};na.defineProperty=sse;var yM=function(t,n){return rse?t.hasOwnProperty(t,n):t[n]===void 0};na.hasOwnProperty=yM;var ase=function(t,n){if(nse)return Object.create(t,n);var r=function(){};r.prototype=t;var i=new r;if(typeof n>"u")return i;if(typeof n=="null")throw new Error("PropertyDescriptors must not be null.");if(typeof n=="object")for(var o in n)yM(n,o)&&(i[o]=n[o].value);return i};na.objectCreate=ase;(function(e){e.__esModule=void 0,e.__esModule=!0;var t=na,n=t.setPrototypeOf,r=t.getPrototypeOf,i=t.defineProperty,o=t.objectCreate,s=new Error().toString()==="[object Error]",a="";function l(u){var c=this.constructor,d=c.name||function(){var S=c.toString().match(/^function\s*([^\s(]+)/);return S===null?a||"Error":S[1]}(),f=d==="Error",h=f?a:d,p=Error.apply(this,arguments);if(n(p,r(this)),!(p instanceof c)||!(p instanceof l)){var p=this;Error.apply(this,arguments),i(p,"message",{configurable:!0,enumerable:!1,value:u,writable:!0})}if(i(p,"name",{configurable:!0,enumerable:!1,value:h,writable:!0}),Error.captureStackTrace&&Error.captureStackTrace(p,f?l:c),p.stack===void 0){var m=new Error(u);m.name=p.name,p.stack=m.stack}return s&&i(p,"toString",{configurable:!0,enumerable:!1,value:function(){return(this.name||"Error")+(typeof this.message>"u"?"":": "+this.message)},writable:!0}),p}a=l.name||"ExtendableError",l.prototype=o(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}}),e.ExtendableError=l,e.default=e.ExtendableError})(mM);var vM=Ee&&Ee.__extends||function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(r[o]=i[o])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}}();Object.defineProperty(rl,"__esModule",{value:!0});rl.SyntaxError=rl.LiqeError=void 0;var lse=mM,bM=function(e){vM(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(lse.ExtendableError);rl.LiqeError=bM;var use=function(e){vM(t,e);function t(n,r,i,o){var s=e.call(this,n)||this;return s.message=n,s.offset=r,s.line=i,s.column=o,s}return t}(bM);rl.SyntaxError=use;var cC={},Vm=Ee&&Ee.__assign||function(){return Vm=Object.assign||function(e){for(var t,n=1,r=arguments.length;n"}],postprocess:function(e){return e.join("")}},{name:"comparison_operator$subexpression$1",symbols:["comparison_operator$subexpression$1$string$2"]},{name:"comparison_operator$subexpression$1$string$3",symbols:[{literal:":"},{literal:"<"}],postprocess:function(e){return e.join("")}},{name:"comparison_operator$subexpression$1",symbols:["comparison_operator$subexpression$1$string$3"]},{name:"comparison_operator$subexpression$1$string$4",symbols:[{literal:":"},{literal:">"},{literal:"="}],postprocess:function(e){return e.join("")}},{name:"comparison_operator$subexpression$1",symbols:["comparison_operator$subexpression$1$string$4"]},{name:"comparison_operator$subexpression$1$string$5",symbols:[{literal:":"},{literal:"<"},{literal:"="}],postprocess:function(e){return e.join("")}},{name:"comparison_operator$subexpression$1",symbols:["comparison_operator$subexpression$1$string$5"]},{name:"comparison_operator",symbols:["comparison_operator$subexpression$1"],postprocess:function(e,t){return{location:{start:t,end:t+e[0][0].length},type:"ComparisonOperator",operator:e[0][0]}}},{name:"regex",symbols:["regex_body","regex_flags"],postprocess:function(e){return e.join("")}},{name:"regex_body$ebnf$1",symbols:[]},{name:"regex_body$ebnf$1",symbols:["regex_body$ebnf$1","regex_body_char"],postprocess:function(e){return e[0].concat([e[1]])}},{name:"regex_body",symbols:[{literal:"/"},"regex_body$ebnf$1",{literal:"/"}],postprocess:function(e){return"/"+e[1].join("")+"/"}},{name:"regex_body_char",symbols:[/[^\\]/],postprocess:po},{name:"regex_body_char",symbols:[{literal:"\\"},/[^\\]/],postprocess:function(e){return"\\"+e[1]}},{name:"regex_flags",symbols:[]},{name:"regex_flags$ebnf$1",symbols:[/[gmiyusd]/]},{name:"regex_flags$ebnf$1",symbols:["regex_flags$ebnf$1",/[gmiyusd]/],postprocess:function(e){return e[0].concat([e[1]])}},{name:"regex_flags",symbols:["regex_flags$ebnf$1"],postprocess:function(e){return e[0].join("")}},{name:"unquoted_value$ebnf$1",symbols:[]},{name:"unquoted_value$ebnf$1",symbols:["unquoted_value$ebnf$1",/[a-zA-Z\.\-_*@#$]/],postprocess:function(e){return e[0].concat([e[1]])}},{name:"unquoted_value",symbols:[/[a-zA-Z_*@#$]/,"unquoted_value$ebnf$1"],postprocess:function(e){return e[0]+e[1].join("")}}],ParserStart:"main"};cC.default=cse;var SM={},G0={},Ch={};Object.defineProperty(Ch,"__esModule",{value:!0});Ch.isSafePath=void 0;var dse=/^(\.(?:[_a-zA-Z][a-zA-Z\d_]*|\0|[1-9]\d*))+$/u,fse=function(e){return dse.test(e)};Ch.isSafePath=fse;Object.defineProperty(G0,"__esModule",{value:!0});G0.createGetValueFunctionBody=void 0;var hse=Ch,pse=function(e){if(!(0,hse.isSafePath)(e))throw new Error("Unsafe path.");var t="return subject"+e;return t.replace(/(\.(\d+))/g,".[$2]").replace(/\./g,"?.")};G0.createGetValueFunctionBody=pse;(function(e){var t=Ee&&Ee.__assign||function(){return t=Object.assign||function(o){for(var s,a=1,l=arguments.length;a\d+) col (?\d+)/,Sse=function(e){if(e.trim()==="")return{location:{end:0,start:0},type:"EmptyExpression"};var t=new wM.default.Parser(vse),n;try{n=t.feed(e).results}catch(o){if(typeof(o==null?void 0:o.message)=="string"&&typeof(o==null?void 0:o.offset)=="number"){var r=o.message.match(bse);throw r?new gse.SyntaxError("Syntax error at line ".concat(r.groups.line," column ").concat(r.groups.column),o.offset,Number(r.groups.line),Number(r.groups.column)):o}throw o}if(n.length===0)throw new Error("Found no parsings.");if(n.length>1)throw new Error("Ambiguous results.");var i=(0,yse.hydrateAst)(n[0]);return i};U0.parse=Sse;var H0={};Object.defineProperty(H0,"__esModule",{value:!0});H0.test=void 0;var _se=wh,wse=function(e,t){return(0,_se.filter)(e,[t]).length===1};H0.test=wse;var xM={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.serialize=void 0;var t=function(o,s){return s==="double"?'"'.concat(o,'"'):s==="single"?"'".concat(o,"'"):o},n=function(o){if(o.type==="LiteralExpression")return o.quoted&&typeof o.value=="string"?t(o.value,o.quotes):String(o.value);if(o.type==="RegexExpression")return String(o.value);if(o.type==="RangeExpression"){var s=o.range,a=s.min,l=s.max,u=s.minInclusive,c=s.maxInclusive;return"".concat(u?"[":"{").concat(a," TO ").concat(l).concat(c?"]":"}")}if(o.type==="EmptyExpression")return"";throw new Error("Unexpected AST type.")},r=function(o){if(o.type!=="Tag")throw new Error("Expected a tag expression.");var s=o.field,a=o.expression,l=o.operator;if(s.type==="ImplicitField")return n(a);var u=s.quoted?t(s.name,s.quotes):s.name,c=" ".repeat(a.location.start-l.location.end);return u+l.operator+c+n(a)},i=function(o){if(o.type==="ParenthesizedExpression"){if(!("location"in o.expression))throw new Error("Expected location in expression.");if(!o.location.end)throw new Error("Expected location end.");var s=" ".repeat(o.expression.location.start-(o.location.start+1)),a=" ".repeat(o.location.end-o.expression.location.end-1);return"(".concat(s).concat((0,e.serialize)(o.expression)).concat(a,")")}if(o.type==="Tag")return r(o);if(o.type==="LogicalExpression"){var l="";return o.operator.type==="BooleanOperator"?(l+=" ".repeat(o.operator.location.start-o.left.location.end),l+=o.operator.operator,l+=" ".repeat(o.right.location.start-o.operator.location.end)):l=" ".repeat(o.right.location.start-o.left.location.end),"".concat((0,e.serialize)(o.left)).concat(l).concat((0,e.serialize)(o.right))}if(o.type==="UnaryOperator")return(o.operator==="NOT"?"NOT ":o.operator)+(0,e.serialize)(o.operand);if(o.type==="EmptyExpression")return"";throw new Error("Unexpected AST type.")};e.serialize=i})(xM);var q0={};Object.defineProperty(q0,"__esModule",{value:!0});q0.isSafeUnquotedExpression=void 0;var xse=function(e){return/^[#$*@A-Z_a-z][#$*.@A-Z_a-z-]*$/.test(e)};q0.isSafeUnquotedExpression=xse;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.isSafeUnquotedExpression=e.serialize=e.SyntaxError=e.LiqeError=e.test=e.parse=e.highlight=e.filter=void 0;var t=wh;Object.defineProperty(e,"filter",{enumerable:!0,get:function(){return t.filter}});var n=z0;Object.defineProperty(e,"highlight",{enumerable:!0,get:function(){return n.highlight}});var r=U0;Object.defineProperty(e,"parse",{enumerable:!0,get:function(){return r.parse}});var i=H0;Object.defineProperty(e,"test",{enumerable:!0,get:function(){return i.test}});var o=rl;Object.defineProperty(e,"LiqeError",{enumerable:!0,get:function(){return o.LiqeError}}),Object.defineProperty(e,"SyntaxError",{enumerable:!0,get:function(){return o.SyntaxError}});var s=xM;Object.defineProperty(e,"serialize",{enumerable:!0,get:function(){return s.serialize}});var a=q0;Object.defineProperty(e,"isSafeUnquotedExpression",{enumerable:!0,get:function(){return a.isSafeUnquotedExpression}})})(pM);var Th={},CM={},il={};Object.defineProperty(il,"__esModule",{value:!0});il.ROARR_LOG_FORMAT_VERSION=il.ROARR_VERSION=void 0;il.ROARR_VERSION="5.0.0";il.ROARR_LOG_FORMAT_VERSION="2.0.0";var Eh={};Object.defineProperty(Eh,"__esModule",{value:!0});Eh.logLevels=void 0;Eh.logLevels={debug:20,error:50,fatal:60,info:30,trace:10,warn:40};var TM={},W0={};Object.defineProperty(W0,"__esModule",{value:!0});W0.hasOwnProperty=void 0;const Cse=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);W0.hasOwnProperty=Cse;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.hasOwnProperty=void 0;var t=W0;Object.defineProperty(e,"hasOwnProperty",{enumerable:!0,get:function(){return t.hasOwnProperty}})})(TM);var EM={},K0={},X0={};Object.defineProperty(X0,"__esModule",{value:!0});X0.tokenize=void 0;const Tse=/(?:%(?([+0-]|-\+))?(?\d+)?(?\d+\$)?(?\.\d+)?(?[%BCESb-iosux]))|(\\%)/g,Ese=e=>{let t;const n=[];let r=0,i=0,o=null;for(;(t=Tse.exec(e))!==null;){t.index>i&&(o={literal:e.slice(i,t.index),type:"literal"},n.push(o));const s=t[0];i=t.index+s.length,s==="\\%"||s==="%%"?o&&o.type==="literal"?o.literal+="%":(o={literal:"%",type:"literal"},n.push(o)):t.groups&&(o={conversion:t.groups.conversion,flag:t.groups.flag||null,placeholder:s,position:t.groups.position?Number.parseInt(t.groups.position,10)-1:r++,precision:t.groups.precision?Number.parseInt(t.groups.precision.slice(1),10):null,type:"placeholder",width:t.groups.width?Number.parseInt(t.groups.width,10):null},n.push(o))}return i<=e.length-1&&(o&&o.type==="literal"?o.literal+=e.slice(i):n.push({literal:e.slice(i),type:"literal"})),n};X0.tokenize=Ese;Object.defineProperty(K0,"__esModule",{value:!0});K0.createPrintf=void 0;const vE=aC,Pse=X0,Ase=(e,t)=>t.placeholder,kse=e=>{var t;const n=(o,s,a)=>a==="-"?o.padEnd(s," "):a==="-+"?((Number(o)>=0?"+":"")+o).padEnd(s," "):a==="+"?((Number(o)>=0?"+":"")+o).padStart(s," "):a==="0"?o.padStart(s,"0"):o.padStart(s," "),r=(t=e==null?void 0:e.formatUnboundExpression)!==null&&t!==void 0?t:Ase,i={};return(o,...s)=>{let a=i[o];a||(a=i[o]=Pse.tokenize(o));let l="";for(const u of a)if(u.type==="literal")l+=u.literal;else{let c=s[u.position];if(c===void 0)l+=r(o,u,s);else if(u.conversion==="b")l+=vE.boolean(c)?"true":"false";else if(u.conversion==="B")l+=vE.boolean(c)?"TRUE":"FALSE";else if(u.conversion==="c")l+=c;else if(u.conversion==="C")l+=String(c).toUpperCase();else if(u.conversion==="i"||u.conversion==="d")c=String(Math.trunc(c)),u.width!==null&&(c=n(c,u.width,u.flag)),l+=c;else if(u.conversion==="e")l+=Number(c).toExponential();else if(u.conversion==="E")l+=Number(c).toExponential().toUpperCase();else if(u.conversion==="f")u.precision!==null&&(c=Number(c).toFixed(u.precision)),u.width!==null&&(c=n(String(c),u.width,u.flag)),l+=c;else if(u.conversion==="o")l+=(Number.parseInt(String(c),10)>>>0).toString(8);else if(u.conversion==="s")u.width!==null&&(c=n(String(c),u.width,u.flag)),l+=c;else if(u.conversion==="S")u.width!==null&&(c=n(String(c),u.width,u.flag)),l+=String(c).toUpperCase();else if(u.conversion==="u")l+=Number.parseInt(String(c),10)>>>0;else if(u.conversion==="x")c=(Number.parseInt(String(c),10)>>>0).toString(16),u.width!==null&&(c=n(String(c),u.width,u.flag)),l+=c;else throw new Error("Unknown format specifier.")}return l}};K0.createPrintf=kse;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.printf=e.createPrintf=void 0;const t=K0;Object.defineProperty(e,"createPrintf",{enumerable:!0,get:function(){return t.createPrintf}}),e.printf=t.createPrintf()})(EM);var l2={exports:{}};(function(e,t){const{hasOwnProperty:n}=Object.prototype,r=S();r.configure=S,r.stringify=r,r.default=r,t.stringify=r,t.configure=S,e.exports=r;const i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/;function o(v){return v.length<5e3&&!i.test(v)?`"${v}"`:JSON.stringify(v)}function s(v){if(v.length>200)return v.sort();for(let y=1;yg;)v[b]=v[b-1],b--;v[b]=g}return v}const a=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function l(v){return a.call(v)!==void 0&&v.length!==0}function u(v,y,g){v.length= 1`)}return g===void 0?1/0:g}function h(v){return v===1?"1 item":`${v} items`}function p(v){const y=new Set;for(const g of v)(typeof g=="string"||typeof g=="number")&&y.add(String(g));return y}function m(v){if(n.call(v,"strict")){const y=v.strict;if(typeof y!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(y)return g=>{let b=`Object can not safely be stringified. Received type ${typeof g}`;throw typeof g!="function"&&(b+=` (${g.toString()})`),new Error(b)}}}function S(v){v={...v};const y=m(v);y&&(v.bigint===void 0&&(v.bigint=!1),"circularValue"in v||(v.circularValue=Error));const g=c(v),b=d(v,"bigint"),_=d(v,"deterministic"),w=f(v,"maximumDepth"),x=f(v,"maximumBreadth");function T(M,C,O,I,N,R){let D=C[M];switch(typeof D=="object"&&D!==null&&typeof D.toJSON=="function"&&(D=D.toJSON(M)),D=I.call(C,M,D),typeof D){case"string":return o(D);case"object":{if(D===null)return"null";if(O.indexOf(D)!==-1)return g;let L="",j=",";const U=R;if(Array.isArray(D)){if(D.length===0)return"[]";if(wx){const ne=D.length-x-1;L+=`${j}"... ${h(ne)} not stringified"`}return N!==""&&(L+=` +${U}`),O.pop(),`[${L}]`}let G=Object.keys(D);const W=G.length;if(W===0)return"{}";if(wx){const H=W-x;L+=`${Y}"...":${X}"${h(H)} not stringified"`,Y=j}return N!==""&&Y.length>1&&(L=` +${R}${L} +${U}`),O.pop(),`{${L}}`}case"number":return isFinite(D)?String(D):y?y(D):"null";case"boolean":return D===!0?"true":"false";case"undefined":return;case"bigint":if(b)return String(D);default:return y?y(D):void 0}}function P(M,C,O,I,N,R){switch(typeof C=="object"&&C!==null&&typeof C.toJSON=="function"&&(C=C.toJSON(M)),typeof C){case"string":return o(C);case"object":{if(C===null)return"null";if(O.indexOf(C)!==-1)return g;const D=R;let L="",j=",";if(Array.isArray(C)){if(C.length===0)return"[]";if(wx){const B=C.length-x-1;L+=`${j}"... ${h(B)} not stringified"`}return N!==""&&(L+=` +${D}`),O.pop(),`[${L}]`}O.push(C);let U="";N!==""&&(R+=N,j=`, +${R}`,U=" ");let G="";for(const W of I){const X=P(W,C[W],O,I,N,R);X!==void 0&&(L+=`${G}${o(W)}:${U}${X}`,G=j)}return N!==""&&G.length>1&&(L=` +${R}${L} +${D}`),O.pop(),`{${L}}`}case"number":return isFinite(C)?String(C):y?y(C):"null";case"boolean":return C===!0?"true":"false";case"undefined":return;case"bigint":if(b)return String(C);default:return y?y(C):void 0}}function E(M,C,O,I,N){switch(typeof C){case"string":return o(C);case"object":{if(C===null)return"null";if(typeof C.toJSON=="function"){if(C=C.toJSON(M),typeof C!="object")return E(M,C,O,I,N);if(C===null)return"null"}if(O.indexOf(C)!==-1)return g;const R=N;if(Array.isArray(C)){if(C.length===0)return"[]";if(wx){const J=C.length-x-1;X+=`${Y}"... ${h(J)} not stringified"`}return X+=` +${R}`,O.pop(),`[${X}]`}let D=Object.keys(C);const L=D.length;if(L===0)return"{}";if(wx){const X=L-x;U+=`${G}"...": "${h(X)} not stringified"`,G=j}return G!==""&&(U=` +${N}${U} +${R}`),O.pop(),`{${U}}`}case"number":return isFinite(C)?String(C):y?y(C):"null";case"boolean":return C===!0?"true":"false";case"undefined":return;case"bigint":if(b)return String(C);default:return y?y(C):void 0}}function A(M,C,O){switch(typeof C){case"string":return o(C);case"object":{if(C===null)return"null";if(typeof C.toJSON=="function"){if(C=C.toJSON(M),typeof C!="object")return A(M,C,O);if(C===null)return"null"}if(O.indexOf(C)!==-1)return g;let I="";if(Array.isArray(C)){if(C.length===0)return"[]";if(wx){const W=C.length-x-1;I+=`,"... ${h(W)} not stringified"`}return O.pop(),`[${I}]`}let N=Object.keys(C);const R=N.length;if(R===0)return"{}";if(wx){const j=R-x;I+=`${D}"...":"${h(j)} not stringified"`}return O.pop(),`{${I}}`}case"number":return isFinite(C)?String(C):y?y(C):"null";case"boolean":return C===!0?"true":"false";case"undefined":return;case"bigint":if(b)return String(C);default:return y?y(C):void 0}}function $(M,C,O){if(arguments.length>1){let I="";if(typeof O=="number"?I=" ".repeat(Math.min(O,10)):typeof O=="string"&&(I=O.slice(0,10)),C!=null){if(typeof C=="function")return T("",{"":M},[],C,I,"");if(Array.isArray(C))return P("",M,[],p(C),I,"")}if(I.length!==0)return E("",M,[],I,"")}return A("",M,[])}return $}})(l2,l2.exports);var Ose=l2.exports;(function(e){var t=Ee&&Ee.__importDefault||function(g){return g&&g.__esModule?g:{default:g}};Object.defineProperty(e,"__esModule",{value:!0}),e.createLogger=void 0;const n=il,r=Eh,i=TM,o=EM,s=t(lC),a=t(Ose);let l=!1;const u=(0,s.default)(),c=()=>u.ROARR,d=()=>({messageContext:{},transforms:[]}),f=()=>{const g=c().asyncLocalStorage;if(!g)throw new Error("AsyncLocalContext is unavailable.");const b=g.getStore();return b||d()},h=()=>!!c().asyncLocalStorage,p=()=>{if(h()){const g=f();return(0,i.hasOwnProperty)(g,"sequenceRoot")&&(0,i.hasOwnProperty)(g,"sequence")&&typeof g.sequence=="number"?String(g.sequenceRoot)+"."+String(g.sequence++):String(c().sequence++)}return String(c().sequence++)},m=(g,b)=>(_,w,x,T,P,E,A,$,M,C)=>{g.child({logLevel:b})(_,w,x,T,P,E,A,$,M,C)},S=1e3,v=(g,b)=>(_,w,x,T,P,E,A,$,M,C)=>{const O=(0,a.default)({a:_,b:w,c:x,d:T,e:P,f:E,g:A,h:$,i:M,j:C,logLevel:b});if(!O)throw new Error("Expected key to be a string");const I=c().onceLog;I.has(O)||(I.add(O),I.size>S&&I.clear(),g.child({logLevel:b})(_,w,x,T,P,E,A,$,M,C))},y=(g,b={},_=[])=>{const w=(x,T,P,E,A,$,M,C,O,I)=>{const N=Date.now(),R=p();let D;h()?D=f():D=d();let L,j;if(typeof x=="string"?L={...D.messageContext,...b}:L={...D.messageContext,...b,...x},typeof x=="string"&&T===void 0)j=x;else if(typeof x=="string"){if(!x.includes("%"))throw new Error("When a string parameter is followed by other arguments, then it is assumed that you are attempting to format a message using printf syntax. You either forgot to add printf bindings or if you meant to add context to the log message, pass them in an object as the first parameter.");j=(0,o.printf)(x,T,P,E,A,$,M,C,O,I)}else{let G=T;if(typeof T!="string")if(T===void 0)G="";else throw new TypeError("Message must be a string. Received "+typeof T+".");j=(0,o.printf)(G,P,E,A,$,M,C,O,I)}let U={context:L,message:j,sequence:R,time:N,version:n.ROARR_LOG_FORMAT_VERSION};for(const G of[...D.transforms,..._])if(U=G(U),typeof U!="object"||U===null)throw new Error("Message transform function must return a message object.");g(U)};return w.child=x=>{let T;return h()?T=f():T=d(),typeof x=="function"?(0,e.createLogger)(g,{...T.messageContext,...b,...x},[x,..._]):(0,e.createLogger)(g,{...T.messageContext,...b,...x},_)},w.getContext=()=>{let x;return h()?x=f():x=d(),{...x.messageContext,...b}},w.adopt=async(x,T)=>{if(!h())return l===!1&&(l=!0,g({context:{logLevel:r.logLevels.warn,package:"roarr"},message:"async_hooks are unavailable; Roarr.adopt will not function as expected",sequence:p(),time:Date.now(),version:n.ROARR_LOG_FORMAT_VERSION})),x();const P=f();let E;(0,i.hasOwnProperty)(P,"sequenceRoot")&&(0,i.hasOwnProperty)(P,"sequence")&&typeof P.sequence=="number"?E=P.sequenceRoot+"."+String(P.sequence++):E=String(c().sequence++);let A={...P.messageContext};const $=[...P.transforms];typeof T=="function"?$.push(T):A={...A,...T};const M=c().asyncLocalStorage;if(!M)throw new Error("Async local context unavailable.");return M.run({messageContext:A,sequence:0,sequenceRoot:E,transforms:$},()=>x())},w.debug=m(w,r.logLevels.debug),w.debugOnce=v(w,r.logLevels.debug),w.error=m(w,r.logLevels.error),w.errorOnce=v(w,r.logLevels.error),w.fatal=m(w,r.logLevels.fatal),w.fatalOnce=v(w,r.logLevels.fatal),w.info=m(w,r.logLevels.info),w.infoOnce=v(w,r.logLevels.info),w.trace=m(w,r.logLevels.trace),w.traceOnce=v(w,r.logLevels.trace),w.warn=m(w,r.logLevels.warn),w.warnOnce=v(w,r.logLevels.warn),w};e.createLogger=y})(CM);var Y0={},Rse=function(t,n){for(var r=t.split("."),i=n.split("."),o=0;o<3;o++){var s=Number(r[o]),a=Number(i[o]);if(s>a)return 1;if(a>s)return-1;if(!isNaN(s)&&isNaN(a))return 1;if(isNaN(s)&&!isNaN(a))return-1}return 0},Ise=Ee&&Ee.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Y0,"__esModule",{value:!0});Y0.createRoarrInitialGlobalStateBrowser=void 0;const bE=il,SE=Ise(Rse),Mse=e=>{const t=(e.versions||[]).concat();return t.length>1&&t.sort(SE.default),t.includes(bE.ROARR_VERSION)||t.push(bE.ROARR_VERSION),t.sort(SE.default),{sequence:0,...e,versions:t}};Y0.createRoarrInitialGlobalStateBrowser=Mse;var Q0={};Object.defineProperty(Q0,"__esModule",{value:!0});Q0.getLogLevelName=void 0;const Nse=e=>e<=10?"trace":e<=20?"debug":e<=30?"info":e<=40?"warn":e<=50?"error":"fatal";Q0.getLogLevelName=Nse;(function(e){var t=Ee&&Ee.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(e,"__esModule",{value:!0}),e.getLogLevelName=e.logLevels=e.Roarr=e.ROARR=void 0;const n=CM,r=Y0,o=(0,t(lC).default)(),s=(0,r.createRoarrInitialGlobalStateBrowser)(o.ROARR||{});e.ROARR=s,o.ROARR=s;const a=d=>JSON.stringify(d),l=(0,n.createLogger)(d=>{var f;s.write&&s.write(((f=s.serializeMessage)!==null&&f!==void 0?f:a)(d))});e.Roarr=l;var u=Eh;Object.defineProperty(e,"logLevels",{enumerable:!0,get:function(){return u.logLevels}});var c=Q0;Object.defineProperty(e,"getLogLevelName",{enumerable:!0,get:function(){return c.getLogLevelName}})})(Th);var Dse=Ee&&Ee.__rest||function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(e);i0?h("%c ".concat(f," %c").concat(c?" [".concat(String(c),"]:"):"","%c ").concat(a.message," %O"),m,S,v,d):h("%c ".concat(f," %c").concat(c?" [".concat(String(c),"]:"):"","%c ").concat(a.message),m,S,v)}}};M0.createLogWriter=Gse;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createLogWriter=void 0;var t=M0;Object.defineProperty(e,"createLogWriter",{enumerable:!0,get:function(){return t.createLogWriter}})})(nM);Th.ROARR.write=nM.createLogWriter();const AM={};Th.Roarr.child(AM);const Z0=T0(Th.Roarr.child(AM)),fe=e=>Z0.get().child({namespace:e}),F3e=["trace","debug","info","warn","error","fatal"],B3e={trace:10,debug:20,info:30,warn:40,error:50,fatal:60};function Hse(){const e=[];return function(t,n){if(typeof n!="object"||n===null)return n;for(;e.length>0&&e.at(-1)!==this;)e.pop();return e.includes(n)?"[Circular]":(e.push(n),n)}}const Df=Vs("nodes/receivedOpenAPISchema",async(e,{dispatch:t,rejectWithValue:n})=>{const r=fe("system");try{const o=await(await fetch("openapi.json")).json();return r.info({openAPISchema:o},"Received OpenAPI schema"),JSON.parse(JSON.stringify(o,Hse()))}catch(i){return n({error:i})}}),kM={nodes:[],edges:[],schema:null,invocationTemplates:{},connectionStartParams:null,shouldShowGraphOverlay:!1,shouldShowFieldTypeLegend:!1,shouldShowMinimapPanel:!0,editorInstance:void 0,progressNodeSize:{width:512,height:512}},OM=Pt({name:"nodes",initialState:kM,reducers:{nodesChanged:(e,t)=>{e.nodes=qI(t.payload,e.nodes)},nodeAdded:(e,t)=>{e.nodes.push(t.payload)},edgesChanged:(e,t)=>{e.edges=nie(t.payload,e.edges)},connectionStarted:(e,t)=>{e.connectionStartParams=t.payload},connectionMade:(e,t)=>{e.edges=bI(t.payload,e.edges)},connectionEnded:e=>{e.connectionStartParams=null},fieldValueChanged:(e,t)=>{const{nodeId:n,fieldName:r,value:i}=t.payload,o=e.nodes.findIndex(s=>s.id===n);o>-1&&(e.nodes[o].data.inputs[r].value=i)},imageCollectionFieldValueChanged:(e,t)=>{const{nodeId:n,fieldName:r,value:i}=t.payload,o=e.nodes.findIndex(a=>a.id===n);if(o===-1)return;const s=Ln(e.nodes[o].data.inputs[r].value);if(!s){e.nodes[o].data.inputs[r].value=i;return}e.nodes[o].data.inputs[r].value=nY(s.concat(i),"image_name")},shouldShowGraphOverlayChanged:(e,t)=>{e.shouldShowGraphOverlay=t.payload},shouldShowFieldTypeLegendChanged:(e,t)=>{e.shouldShowFieldTypeLegend=t.payload},shouldShowMinimapPanelChanged:(e,t)=>{e.shouldShowMinimapPanel=t.payload},nodeTemplatesBuilt:(e,t)=>{e.invocationTemplates=t.payload},nodeEditorReset:e=>{e.nodes=[],e.edges=[]},setEditorInstance:(e,t)=>{e.editorInstance=t.payload},loadFileNodes:(e,t)=>{e.nodes=t.payload},loadFileEdges:(e,t)=>{e.edges=t.payload},setProgressNodeSize:(e,t)=>{e.progressNodeSize=t.payload}},extraReducers:e=>{e.addCase(Df.fulfilled,(t,n)=>{t.schema=n.payload})}}),{nodesChanged:j3e,edgesChanged:V3e,nodeAdded:z3e,fieldValueChanged:u2,connectionMade:U3e,connectionStarted:G3e,connectionEnded:H3e,shouldShowGraphOverlayChanged:q3e,shouldShowFieldTypeLegendChanged:W3e,shouldShowMinimapPanelChanged:K3e,nodeTemplatesBuilt:dC,nodeEditorReset:RM,imageCollectionFieldValueChanged:X3e,setEditorInstance:Y3e,loadFileNodes:Q3e,loadFileEdges:Z3e,setProgressNodeSize:J3e}=OM.actions,qse=OM.reducer,IM={esrganModelName:"RealESRGAN_x4plus.pth"},MM=Pt({name:"postprocessing",initialState:IM,reducers:{esrganModelNameChanged:(e,t)=>{e.esrganModelName=t.payload}}}),{esrganModelNameChanged:e5e}=MM.actions,Wse=MM.reducer,Kse={positiveStylePrompt:"",negativeStylePrompt:"",shouldConcatSDXLStylePrompt:!0,shouldUseSDXLRefiner:!1,sdxlImg2ImgDenoisingStrength:.7,refinerModel:null,refinerSteps:20,refinerCFGScale:7.5,refinerScheduler:"euler",refinerAestheticScore:6,refinerStart:.7},NM=Pt({name:"sdxl",initialState:Kse,reducers:{setPositiveStylePromptSDXL:(e,t)=>{e.positiveStylePrompt=t.payload},setNegativeStylePromptSDXL:(e,t)=>{e.negativeStylePrompt=t.payload},setShouldConcatSDXLStylePrompt:(e,t)=>{e.shouldConcatSDXLStylePrompt=t.payload},setShouldUseSDXLRefiner:(e,t)=>{e.shouldUseSDXLRefiner=t.payload},setSDXLImg2ImgDenoisingStrength:(e,t)=>{e.sdxlImg2ImgDenoisingStrength=t.payload},refinerModelChanged:(e,t)=>{e.refinerModel=t.payload},setRefinerSteps:(e,t)=>{e.refinerSteps=t.payload},setRefinerCFGScale:(e,t)=>{e.refinerCFGScale=t.payload},setRefinerScheduler:(e,t)=>{e.refinerScheduler=t.payload},setRefinerAestheticScore:(e,t)=>{e.refinerAestheticScore=t.payload},setRefinerStart:(e,t)=>{e.refinerStart=t.payload}}}),{setPositiveStylePromptSDXL:t5e,setNegativeStylePromptSDXL:n5e,setShouldConcatSDXLStylePrompt:r5e,setShouldUseSDXLRefiner:Xse,setSDXLImg2ImgDenoisingStrength:i5e,refinerModelChanged:wE,setRefinerSteps:o5e,setRefinerCFGScale:s5e,setRefinerScheduler:a5e,setRefinerAestheticScore:l5e,setRefinerStart:u5e}=NM.actions,Yse=NM.reducer,Ph=ue("app/userInvoked"),Qse={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console&&console[e]&&console[e].apply(console,t)}};class zm{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.init(t,n)}init(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.prefix=n.prefix||"i18next:",this.logger=t||Qse,this.options=n,this.debug=n.debug}log(){for(var t=arguments.length,n=new Array(t),r=0;r{this.observers[r]=this.observers[r]||[],this.observers[r].push(n)}),this}off(t,n){if(this.observers[t]){if(!n){delete this.observers[t];return}this.observers[t]=this.observers[t].filter(r=>r!==n)}}emit(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i{s(...r)}),this.observers["*"]&&[].concat(this.observers["*"]).forEach(s=>{s.apply(s,[t,...r])})}}function Xc(){let e,t;const n=new Promise((r,i)=>{e=r,t=i});return n.resolve=e,n.reject=t,n}function xE(e){return e==null?"":""+e}function Zse(e,t,n){e.forEach(r=>{t[r]&&(n[r]=t[r])})}function fC(e,t,n){function r(s){return s&&s.indexOf("###")>-1?s.replace(/###/g,"."):s}function i(){return!e||typeof e=="string"}const o=typeof t!="string"?[].concat(t):t.split(".");for(;o.length>1;){if(i())return{};const s=r(o.shift());!e[s]&&n&&(e[s]=new n),Object.prototype.hasOwnProperty.call(e,s)?e=e[s]:e={}}return i()?{}:{obj:e,k:r(o.shift())}}function CE(e,t,n){const{obj:r,k:i}=fC(e,t,Object);r[i]=n}function Jse(e,t,n,r){const{obj:i,k:o}=fC(e,t,Object);i[o]=i[o]||[],r&&(i[o]=i[o].concat(n)),r||i[o].push(n)}function Um(e,t){const{obj:n,k:r}=fC(e,t);if(n)return n[r]}function eae(e,t,n){const r=Um(e,n);return r!==void 0?r:Um(t,n)}function DM(e,t,n){for(const r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?typeof e[r]=="string"||e[r]instanceof String||typeof t[r]=="string"||t[r]instanceof String?n&&(e[r]=t[r]):DM(e[r],t[r],n):e[r]=t[r]);return e}function jl(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}var tae={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};function nae(e){return typeof e=="string"?e.replace(/[&<>"'\/]/g,t=>tae[t]):e}const rae=[" ",",","?","!",";"];function iae(e,t,n){t=t||"",n=n||"";const r=rae.filter(s=>t.indexOf(s)<0&&n.indexOf(s)<0);if(r.length===0)return!0;const i=new RegExp(`(${r.map(s=>s==="?"?"\\?":s).join("|")})`);let o=!i.test(e);if(!o){const s=e.indexOf(n);s>0&&!i.test(e.substring(0,s))&&(o=!0)}return o}function Gm(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:".";if(!e)return;if(e[t])return e[t];const r=t.split(n);let i=e;for(let o=0;oo+s;)s++,a=r.slice(o,o+s).join(n),l=i[a];if(l===void 0)return;if(l===null)return null;if(t.endsWith(a)){if(typeof l=="string")return l;if(a&&typeof l[a]=="string")return l[a]}const u=r.slice(o+s).join(n);return u?Gm(l,u,n):void 0}i=i[r[o]]}return i}function Hm(e){return e&&e.indexOf("_")>0?e.replace("_","-"):e}class TE extends J0{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{ns:["translation"],defaultNS:"translation"};super(),this.data=t||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const n=this.options.ns.indexOf(t);n>-1&&this.options.ns.splice(n,1)}getResource(t,n,r){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const o=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,s=i.ignoreJSONStructure!==void 0?i.ignoreJSONStructure:this.options.ignoreJSONStructure;let a=[t,n];r&&typeof r!="string"&&(a=a.concat(r)),r&&typeof r=="string"&&(a=a.concat(o?r.split(o):r)),t.indexOf(".")>-1&&(a=t.split("."));const l=Um(this.data,a);return l||!s||typeof r!="string"?l:Gm(this.data&&this.data[t]&&this.data[t][n],r,o)}addResource(t,n,r,i){let o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{silent:!1};const s=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator;let a=[t,n];r&&(a=a.concat(s?r.split(s):r)),t.indexOf(".")>-1&&(a=t.split("."),i=n,n=a[1]),this.addNamespaces(n),CE(this.data,a,i),o.silent||this.emit("added",t,n,r,i)}addResources(t,n,r){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{silent:!1};for(const o in r)(typeof r[o]=="string"||Object.prototype.toString.apply(r[o])==="[object Array]")&&this.addResource(t,n,o,r[o],{silent:!0});i.silent||this.emit("added",t,n,r)}addResourceBundle(t,n,r,i,o){let s=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{silent:!1},a=[t,n];t.indexOf(".")>-1&&(a=t.split("."),i=r,r=n,n=a[1]),this.addNamespaces(n);let l=Um(this.data,a)||{};i?DM(l,r,o):l={...l,...r},CE(this.data,a,l),s.silent||this.emit("added",t,n,r)}removeResourceBundle(t,n){this.hasResourceBundle(t,n)&&delete this.data[t][n],this.removeNamespaces(n),this.emit("removed",t,n)}hasResourceBundle(t,n){return this.getResource(t,n)!==void 0}getResourceBundle(t,n){return n||(n=this.options.defaultNS),this.options.compatibilityAPI==="v1"?{...this.getResource(t,n)}:this.getResource(t,n)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const n=this.getDataByLanguage(t);return!!(n&&Object.keys(n)||[]).find(i=>n[i]&&Object.keys(n[i]).length>0)}toJSON(){return this.data}}var LM={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,i){return e.forEach(o=>{this.processors[o]&&(t=this.processors[o].process(t,n,r,i))}),t}};const EE={};class qm extends J0{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Zse(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=qi.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}};if(t==null)return!1;const r=this.resolve(t,n);return r&&r.res!==void 0}extractFromKey(t,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const i=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let o=n.ns||this.options.defaultNS||[];const s=r&&t.indexOf(r)>-1,a=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!iae(t,r,i);if(s&&!a){const l=t.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:t,namespaces:o};const u=t.split(r);(r!==i||r===i&&this.options.ns.indexOf(u[0])>-1)&&(o=u.shift()),t=u.join(i)}return typeof o=="string"&&(o=[o]),{key:t,namespaces:o}}translate(t,n,r){if(typeof n!="object"&&this.options.overloadTranslationOptionHandler&&(n=this.options.overloadTranslationOptionHandler(arguments)),typeof n=="object"&&(n={...n}),n||(n={}),t==null)return"";Array.isArray(t)||(t=[String(t)]);const i=n.returnDetails!==void 0?n.returnDetails:this.options.returnDetails,o=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator,{key:s,namespaces:a}=this.extractFromKey(t[t.length-1],n),l=a[a.length-1],u=n.lng||this.language,c=n.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(u&&u.toLowerCase()==="cimode"){if(c){const b=n.nsSeparator||this.options.nsSeparator;return i?{res:`${l}${b}${s}`,usedKey:s,exactUsedKey:s,usedLng:u,usedNS:l}:`${l}${b}${s}`}return i?{res:s,usedKey:s,exactUsedKey:s,usedLng:u,usedNS:l}:s}const d=this.resolve(t,n);let f=d&&d.res;const h=d&&d.usedKey||s,p=d&&d.exactUsedKey||s,m=Object.prototype.toString.apply(f),S=["[object Number]","[object Function]","[object RegExp]"],v=n.joinArrays!==void 0?n.joinArrays:this.options.joinArrays,y=!this.i18nFormat||this.i18nFormat.handleAsObject;if(y&&f&&(typeof f!="string"&&typeof f!="boolean"&&typeof f!="number")&&S.indexOf(m)<0&&!(typeof v=="string"&&m==="[object Array]")){if(!n.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const b=this.options.returnedObjectHandler?this.options.returnedObjectHandler(h,f,{...n,ns:a}):`key '${s} (${this.language})' returned an object instead of string.`;return i?(d.res=b,d):b}if(o){const b=m==="[object Array]",_=b?[]:{},w=b?p:h;for(const x in f)if(Object.prototype.hasOwnProperty.call(f,x)){const T=`${w}${o}${x}`;_[x]=this.translate(T,{...n,joinArrays:!1,ns:a}),_[x]===T&&(_[x]=f[x])}f=_}}else if(y&&typeof v=="string"&&m==="[object Array]")f=f.join(v),f&&(f=this.extendTranslation(f,t,n,r));else{let b=!1,_=!1;const w=n.count!==void 0&&typeof n.count!="string",x=qm.hasDefaultValue(n),T=w?this.pluralResolver.getSuffix(u,n.count,n):"",P=n.ordinal&&w?this.pluralResolver.getSuffix(u,n.count,{ordinal:!1}):"",E=n[`defaultValue${T}`]||n[`defaultValue${P}`]||n.defaultValue;!this.isValidLookup(f)&&x&&(b=!0,f=E),this.isValidLookup(f)||(_=!0,f=s);const $=(n.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&_?void 0:f,M=x&&E!==f&&this.options.updateMissing;if(_||b||M){if(this.logger.log(M?"updateKey":"missingKey",u,l,s,M?E:f),o){const N=this.resolve(s,{...n,keySeparator:!1});N&&N.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let C=[];const O=this.languageUtils.getFallbackCodes(this.options.fallbackLng,n.lng||this.language);if(this.options.saveMissingTo==="fallback"&&O&&O[0])for(let N=0;N{const L=x&&D!==f?D:$;this.options.missingKeyHandler?this.options.missingKeyHandler(N,l,R,L,M,n):this.backendConnector&&this.backendConnector.saveMissing&&this.backendConnector.saveMissing(N,l,R,L,M,n),this.emit("missingKey",N,l,R,f)};this.options.saveMissing&&(this.options.saveMissingPlurals&&w?C.forEach(N=>{this.pluralResolver.getSuffixes(N,n).forEach(R=>{I([N],s+R,n[`defaultValue${R}`]||E)})}):I(C,s,E))}f=this.extendTranslation(f,t,n,d,r),_&&f===s&&this.options.appendNamespaceToMissingKey&&(f=`${l}:${s}`),(_||b)&&this.options.parseMissingKeyHandler&&(this.options.compatibilityAPI!=="v1"?f=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}:${s}`:s,b?f:void 0):f=this.options.parseMissingKeyHandler(f))}return i?(d.res=f,d):f}extendTranslation(t,n,r,i,o){var s=this;if(this.i18nFormat&&this.i18nFormat.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...r},i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const u=typeof t=="string"&&(r&&r.interpolation&&r.interpolation.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let c;if(u){const f=t.match(this.interpolator.nestingRegexp);c=f&&f.length}let d=r.replace&&typeof r.replace!="string"?r.replace:r;if(this.options.interpolation.defaultVariables&&(d={...this.options.interpolation.defaultVariables,...d}),t=this.interpolator.interpolate(t,d,r.lng||this.language,r),u){const f=t.match(this.interpolator.nestingRegexp),h=f&&f.length;c1&&arguments[1]!==void 0?arguments[1]:{},r,i,o,s,a;return typeof t=="string"&&(t=[t]),t.forEach(l=>{if(this.isValidLookup(r))return;const u=this.extractFromKey(l,n),c=u.key;i=c;let d=u.namespaces;this.options.fallbackNS&&(d=d.concat(this.options.fallbackNS));const f=n.count!==void 0&&typeof n.count!="string",h=f&&!n.ordinal&&n.count===0&&this.pluralResolver.shouldUseIntlApi(),p=n.context!==void 0&&(typeof n.context=="string"||typeof n.context=="number")&&n.context!=="",m=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);d.forEach(S=>{this.isValidLookup(r)||(a=S,!EE[`${m[0]}-${S}`]&&this.utils&&this.utils.hasLoadedNamespace&&!this.utils.hasLoadedNamespace(a)&&(EE[`${m[0]}-${S}`]=!0,this.logger.warn(`key "${i}" for languages "${m.join(", ")}" won't get resolved as namespace "${a}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),m.forEach(v=>{if(this.isValidLookup(r))return;s=v;const y=[c];if(this.i18nFormat&&this.i18nFormat.addLookupKeys)this.i18nFormat.addLookupKeys(y,c,v,S,n);else{let b;f&&(b=this.pluralResolver.getSuffix(v,n.count,n));const _=`${this.options.pluralSeparator}zero`,w=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(f&&(y.push(c+b),n.ordinal&&b.indexOf(w)===0&&y.push(c+b.replace(w,this.options.pluralSeparator)),h&&y.push(c+_)),p){const x=`${c}${this.options.contextSeparator}${n.context}`;y.push(x),f&&(y.push(x+b),n.ordinal&&b.indexOf(w)===0&&y.push(x+b.replace(w,this.options.pluralSeparator)),h&&y.push(x+_))}}let g;for(;g=y.pop();)this.isValidLookup(r)||(o=g,r=this.getResource(v,S,g,n))}))})}),{res:r,usedKey:i,exactUsedKey:o,usedLng:s,usedNS:a}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,n,r){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(t,n,r,i):this.resourceStore.getResource(t,n,r,i)}static hasDefaultValue(t){const n="defaultValue";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&n===r.substring(0,n.length)&&t[r]!==void 0)return!0;return!1}}function $b(e){return e.charAt(0).toUpperCase()+e.slice(1)}class PE{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=qi.create("languageUtils")}getScriptPartFromCode(t){if(t=Hm(t),!t||t.indexOf("-")<0)return null;const n=t.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(t){if(t=Hm(t),!t||t.indexOf("-")<0)return t;const n=t.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(t){if(typeof t=="string"&&t.indexOf("-")>-1){const n=["hans","hant","latn","cyrl","cans","mong","arab"];let r=t.split("-");return this.options.lowerCaseLng?r=r.map(i=>i.toLowerCase()):r.length===2?(r[0]=r[0].toLowerCase(),r[1]=r[1].toUpperCase(),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=$b(r[1].toLowerCase()))):r.length===3&&(r[0]=r[0].toLowerCase(),r[1].length===2&&(r[1]=r[1].toUpperCase()),r[0]!=="sgn"&&r[2].length===2&&(r[2]=r[2].toUpperCase()),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=$b(r[1].toLowerCase())),n.indexOf(r[2].toLowerCase())>-1&&(r[2]=$b(r[2].toLowerCase()))),r.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let n;return t.forEach(r=>{if(n)return;const i=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(i))&&(n=i)}),!n&&this.options.supportedLngs&&t.forEach(r=>{if(n)return;const i=this.getLanguagePartFromCode(r);if(this.isSupportedCode(i))return n=i;n=this.options.supportedLngs.find(o=>{if(o===i)return o;if(!(o.indexOf("-")<0&&i.indexOf("-")<0)&&o.indexOf(i)===0)return o})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(t,n){if(!t)return[];if(typeof t=="function"&&(t=t(n)),typeof t=="string"&&(t=[t]),Object.prototype.toString.apply(t)==="[object Array]")return t;if(!n)return t.default||[];let r=t[n];return r||(r=t[this.getScriptPartFromCode(n)]),r||(r=t[this.formatLanguageCode(n)]),r||(r=t[this.getLanguagePartFromCode(n)]),r||(r=t.default),r||[]}toResolveHierarchy(t,n){const r=this.getFallbackCodes(n||this.options.fallbackLng||[],t),i=[],o=s=>{s&&(this.isSupportedCode(s)?i.push(s):this.logger.warn(`rejecting language code not found in supportedLngs: ${s}`))};return typeof t=="string"&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&o(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&o(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&o(this.getLanguagePartFromCode(t))):typeof t=="string"&&o(this.formatLanguageCode(t)),r.forEach(s=>{i.indexOf(s)<0&&o(this.formatLanguageCode(s))}),i}}let oae=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],sae={1:function(e){return+(e>1)},2:function(e){return+(e!=1)},3:function(e){return 0},4:function(e){return e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2},5:function(e){return e==0?0:e==1?1:e==2?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5},6:function(e){return e==1?0:e>=2&&e<=4?1:2},7:function(e){return e==1?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2},8:function(e){return e==1?0:e==2?1:e!=8&&e!=11?2:3},9:function(e){return+(e>=2)},10:function(e){return e==1?0:e==2?1:e<7?2:e<11?3:4},11:function(e){return e==1||e==11?0:e==2||e==12?1:e>2&&e<20?2:3},12:function(e){return+(e%10!=1||e%100==11)},13:function(e){return+(e!==0)},14:function(e){return e==1?0:e==2?1:e==3?2:3},15:function(e){return e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2},16:function(e){return e%10==1&&e%100!=11?0:e!==0?1:2},17:function(e){return e==1||e%10==1&&e%100!=11?0:1},18:function(e){return e==0?0:e==1?1:2},19:function(e){return e==1?0:e==0||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3},20:function(e){return e==1?0:e==0||e%100>0&&e%100<20?1:2},21:function(e){return e%100==1?1:e%100==2?2:e%100==3||e%100==4?3:0},22:function(e){return e==1?0:e==2?1:(e<0||e>10)&&e%10==0?2:3}};const aae=["v1","v2","v3"],lae=["v4"],AE={zero:0,one:1,two:2,few:3,many:4,other:5};function uae(){const e={};return oae.forEach(t=>{t.lngs.forEach(n=>{e[n]={numbers:t.nr,plurals:sae[t.fc]}})}),e}class cae{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.languageUtils=t,this.options=n,this.logger=qi.create("pluralResolver"),(!this.options.compatibilityJSON||lae.includes(this.options.compatibilityJSON))&&(typeof Intl>"u"||!Intl.PluralRules)&&(this.options.compatibilityJSON="v3",this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")),this.rules=uae()}addRule(t,n){this.rules[t]=n}getRule(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.shouldUseIntlApi())try{return new Intl.PluralRules(Hm(t),{type:n.ordinal?"ordinal":"cardinal"})}catch{return}return this.rules[t]||this.rules[this.languageUtils.getLanguagePartFromCode(t)]}needsPlural(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return this.shouldUseIntlApi()?r&&r.resolvedOptions().pluralCategories.length>1:r&&r.numbers.length>1}getPluralFormsOfKey(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this.getSuffixes(t,r).map(i=>`${n}${i}`)}getSuffixes(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return r?this.shouldUseIntlApi()?r.resolvedOptions().pluralCategories.sort((i,o)=>AE[i]-AE[o]).map(i=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i}`):r.numbers.map(i=>this.getSuffix(t,i,n)):[]}getSuffix(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=this.getRule(t,r);return i?this.shouldUseIntlApi()?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${i.select(n)}`:this.getSuffixRetroCompatible(i,n):(this.logger.warn(`no plural rule found for: ${t}`),"")}getSuffixRetroCompatible(t,n){const r=t.noAbs?t.plurals(n):t.plurals(Math.abs(n));let i=t.numbers[r];this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1&&(i===2?i="plural":i===1&&(i=""));const o=()=>this.options.prepend&&i.toString()?this.options.prepend+i.toString():i.toString();return this.options.compatibilityJSON==="v1"?i===1?"":typeof i=="number"?`_plural_${i.toString()}`:o():this.options.compatibilityJSON==="v2"||this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1?o():this.options.prepend&&r.toString()?this.options.prepend+r.toString():r.toString()}shouldUseIntlApi(){return!aae.includes(this.options.compatibilityJSON)}}function kE(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:".",i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,o=eae(e,t,n);return!o&&i&&typeof n=="string"&&(o=Gm(e,n,r),o===void 0&&(o=Gm(t,n,r))),o}class dae{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=qi.create("interpolator"),this.options=t,this.format=t.interpolation&&t.interpolation.format||(n=>n),this.init(t)}init(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};t.interpolation||(t.interpolation={escapeValue:!0});const n=t.interpolation;this.escape=n.escape!==void 0?n.escape:nae,this.escapeValue=n.escapeValue!==void 0?n.escapeValue:!0,this.useRawValueToEscape=n.useRawValueToEscape!==void 0?n.useRawValueToEscape:!1,this.prefix=n.prefix?jl(n.prefix):n.prefixEscaped||"{{",this.suffix=n.suffix?jl(n.suffix):n.suffixEscaped||"}}",this.formatSeparator=n.formatSeparator?n.formatSeparator:n.formatSeparator||",",this.unescapePrefix=n.unescapeSuffix?"":n.unescapePrefix||"-",this.unescapeSuffix=this.unescapePrefix?"":n.unescapeSuffix||"",this.nestingPrefix=n.nestingPrefix?jl(n.nestingPrefix):n.nestingPrefixEscaped||jl("$t("),this.nestingSuffix=n.nestingSuffix?jl(n.nestingSuffix):n.nestingSuffixEscaped||jl(")"),this.nestingOptionsSeparator=n.nestingOptionsSeparator?n.nestingOptionsSeparator:n.nestingOptionsSeparator||",",this.maxReplaces=n.maxReplaces?n.maxReplaces:1e3,this.alwaysFormat=n.alwaysFormat!==void 0?n.alwaysFormat:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=`${this.prefix}(.+?)${this.suffix}`;this.regexp=new RegExp(t,"g");const n=`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`;this.regexpUnescape=new RegExp(n,"g");const r=`${this.nestingPrefix}(.+?)${this.nestingSuffix}`;this.nestingRegexp=new RegExp(r,"g")}interpolate(t,n,r,i){let o,s,a;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{};function u(p){return p.replace(/\$/g,"$$$$")}const c=p=>{if(p.indexOf(this.formatSeparator)<0){const y=kE(n,l,p,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(y,void 0,r,{...i,...n,interpolationkey:p}):y}const m=p.split(this.formatSeparator),S=m.shift().trim(),v=m.join(this.formatSeparator).trim();return this.format(kE(n,l,S,this.options.keySeparator,this.options.ignoreJSONStructure),v,r,{...i,...n,interpolationkey:S})};this.resetRegExp();const d=i&&i.missingInterpolationHandler||this.options.missingInterpolationHandler,f=i&&i.interpolation&&i.interpolation.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:p=>u(p)},{regex:this.regexp,safeValue:p=>this.escapeValue?u(this.escape(p)):u(p)}].forEach(p=>{for(a=0;o=p.regex.exec(t);){const m=o[1].trim();if(s=c(m),s===void 0)if(typeof d=="function"){const v=d(t,o,i);s=typeof v=="string"?v:""}else if(i&&Object.prototype.hasOwnProperty.call(i,m))s="";else if(f){s=o[0];continue}else this.logger.warn(`missed to pass in variable ${m} for interpolating ${t}`),s="";else typeof s!="string"&&!this.useRawValueToEscape&&(s=xE(s));const S=p.safeValue(s);if(t=t.replace(o[0],S),f?(p.regex.lastIndex+=s.length,p.regex.lastIndex-=o[0].length):p.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),t}nest(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i,o,s;function a(l,u){const c=this.nestingOptionsSeparator;if(l.indexOf(c)<0)return l;const d=l.split(new RegExp(`${c}[ ]*{`));let f=`{${d[1]}`;l=d[0],f=this.interpolate(f,s);const h=f.match(/'/g),p=f.match(/"/g);(h&&h.length%2===0&&!p||p.length%2!==0)&&(f=f.replace(/'/g,'"'));try{s=JSON.parse(f),u&&(s={...u,...s})}catch(m){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,m),`${l}${c}${f}`}return delete s.defaultValue,l}for(;i=this.nestingRegexp.exec(t);){let l=[];s={...r},s=s.replace&&typeof s.replace!="string"?s.replace:s,s.applyPostProcessor=!1,delete s.defaultValue;let u=!1;if(i[0].indexOf(this.formatSeparator)!==-1&&!/{.*}/.test(i[1])){const c=i[1].split(this.formatSeparator).map(d=>d.trim());i[1]=c.shift(),l=c,u=!0}if(o=n(a.call(this,i[1].trim(),s),s),o&&i[0]===t&&typeof o!="string")return o;typeof o!="string"&&(o=xE(o)),o||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${t}`),o=""),u&&(o=l.reduce((c,d)=>this.format(c,d,r.lng,{...r,interpolationkey:i[1].trim()}),o.trim())),t=t.replace(i[0],o),this.regexp.lastIndex=0}return t}}function fae(e){let t=e.toLowerCase().trim();const n={};if(e.indexOf("(")>-1){const r=e.split("(");t=r[0].toLowerCase().trim();const i=r[1].substring(0,r[1].length-1);t==="currency"&&i.indexOf(":")<0?n.currency||(n.currency=i.trim()):t==="relativetime"&&i.indexOf(":")<0?n.range||(n.range=i.trim()):i.split(";").forEach(s=>{if(!s)return;const[a,...l]=s.split(":"),u=l.join(":").trim().replace(/^'+|'+$/g,"");n[a.trim()]||(n[a.trim()]=u),u==="false"&&(n[a.trim()]=!1),u==="true"&&(n[a.trim()]=!0),isNaN(u)||(n[a.trim()]=parseInt(u,10))})}return{formatName:t,formatOptions:n}}function Vl(e){const t={};return function(r,i,o){const s=i+JSON.stringify(o);let a=t[s];return a||(a=e(Hm(i),o),t[s]=a),a(r)}}class hae{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=qi.create("formatter"),this.options=t,this.formats={number:Vl((n,r)=>{const i=new Intl.NumberFormat(n,{...r});return o=>i.format(o)}),currency:Vl((n,r)=>{const i=new Intl.NumberFormat(n,{...r,style:"currency"});return o=>i.format(o)}),datetime:Vl((n,r)=>{const i=new Intl.DateTimeFormat(n,{...r});return o=>i.format(o)}),relativetime:Vl((n,r)=>{const i=new Intl.RelativeTimeFormat(n,{...r});return o=>i.format(o,r.range||"day")}),list:Vl((n,r)=>{const i=new Intl.ListFormat(n,{...r});return o=>i.format(o)})},this.init(t)}init(t){const r=(arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}}).interpolation;this.formatSeparator=r.formatSeparator?r.formatSeparator:r.formatSeparator||","}add(t,n){this.formats[t.toLowerCase().trim()]=n}addCached(t,n){this.formats[t.toLowerCase().trim()]=Vl(n)}format(t,n,r){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return n.split(this.formatSeparator).reduce((a,l)=>{const{formatName:u,formatOptions:c}=fae(l);if(this.formats[u]){let d=a;try{const f=i&&i.formatParams&&i.formatParams[i.interpolationkey]||{},h=f.locale||f.lng||i.locale||i.lng||r;d=this.formats[u](a,h,{...c,...i,...f})}catch(f){this.logger.warn(f)}return d}else this.logger.warn(`there was no format function for ${u}`);return a},t)}}function pae(e,t){e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)}class gae extends J0{constructor(t,n,r){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};super(),this.backend=t,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=i,this.logger=qi.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],this.backend&&this.backend.init&&this.backend.init(r,i.backend,i)}queueLoad(t,n,r,i){const o={},s={},a={},l={};return t.forEach(u=>{let c=!0;n.forEach(d=>{const f=`${u}|${d}`;!r.reload&&this.store.hasResourceBundle(u,d)?this.state[f]=2:this.state[f]<0||(this.state[f]===1?s[f]===void 0&&(s[f]=!0):(this.state[f]=1,c=!1,s[f]===void 0&&(s[f]=!0),o[f]===void 0&&(o[f]=!0),l[d]===void 0&&(l[d]=!0)))}),c||(a[u]=!0)}),(Object.keys(o).length||Object.keys(s).length)&&this.queue.push({pending:s,pendingCount:Object.keys(s).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(o),pending:Object.keys(s),toLoadLanguages:Object.keys(a),toLoadNamespaces:Object.keys(l)}}loaded(t,n,r){const i=t.split("|"),o=i[0],s=i[1];n&&this.emit("failedLoading",o,s,n),r&&this.store.addResourceBundle(o,s,r),this.state[t]=n?-1:2;const a={};this.queue.forEach(l=>{Jse(l.loaded,[o],s),pae(l,t),n&&l.errors.push(n),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(u=>{a[u]||(a[u]={});const c=l.loaded[u];c.length&&c.forEach(d=>{a[u][d]===void 0&&(a[u][d]=!0)})}),l.done=!0,l.errors.length?l.callback(l.errors):l.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(l=>!l.done)}read(t,n,r){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:this.retryTimeout,s=arguments.length>5?arguments[5]:void 0;if(!t.length)return s(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:n,fcName:r,tried:i,wait:o,callback:s});return}this.readingCalls++;const a=(u,c)=>{if(this.readingCalls--,this.waitingReads.length>0){const d=this.waitingReads.shift();this.read(d.lng,d.ns,d.fcName,d.tried,d.wait,d.callback)}if(u&&c&&i{this.read.call(this,t,n,r,i+1,o*2,s)},o);return}s(u,c)},l=this.backend[r].bind(this.backend);if(l.length===2){try{const u=l(t,n);u&&typeof u.then=="function"?u.then(c=>a(null,c)).catch(a):a(null,u)}catch(u){a(u)}return}return l(t,n,a)}prepareLoading(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();typeof t=="string"&&(t=this.languageUtils.toResolveHierarchy(t)),typeof n=="string"&&(n=[n]);const o=this.queueLoad(t,n,r,i);if(!o.toLoad.length)return o.pending.length||i(),null;o.toLoad.forEach(s=>{this.loadOne(s)})}load(t,n,r){this.prepareLoading(t,n,{},r)}reload(t,n,r){this.prepareLoading(t,n,{reload:!0},r)}loadOne(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const r=t.split("|"),i=r[0],o=r[1];this.read(i,o,"read",void 0,void 0,(s,a)=>{s&&this.logger.warn(`${n}loading namespace ${o} for language ${i} failed`,s),!s&&a&&this.logger.log(`${n}loaded namespace ${o} for language ${i}`,a),this.loaded(t,s,a)})}saveMissing(t,n,r,i,o){let s=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{},a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:()=>{};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend&&this.backend.create){const l={...s,isUpdate:o},u=this.backend.create.bind(this.backend);if(u.length<6)try{let c;u.length===5?c=u(t,n,r,i,l):c=u(t,n,r,i),c&&typeof c.then=="function"?c.then(d=>a(null,d)).catch(a):a(null,c)}catch(c){a(c)}else u(t,n,r,i,a,l)}!t||!t[0]||this.store.addResource(t[0],n,r,i)}}}function OE(){return{debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:function(t){let n={};if(typeof t[1]=="object"&&(n=t[1]),typeof t[1]=="string"&&(n.defaultValue=t[1]),typeof t[2]=="string"&&(n.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const r=t[3]||t[2];Object.keys(r).forEach(i=>{n[i]=r[i]})}return n},interpolation:{escapeValue:!0,format:(e,t,n,r)=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0}}}function RE(e){return typeof e.ns=="string"&&(e.ns=[e.ns]),typeof e.fallbackLng=="string"&&(e.fallbackLng=[e.fallbackLng]),typeof e.fallbackNS=="string"&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs&&e.supportedLngs.indexOf("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),e}function Op(){}function mae(e){Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(n=>{typeof e[n]=="function"&&(e[n]=e[n].bind(e))})}class Lf extends J0{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;if(super(),this.options=RE(t),this.services={},this.logger=qi,this.modules={external:[]},mae(this),n&&!this.isInitialized&&!t.isClone){if(!this.options.initImmediate)return this.init(t,n),this;setTimeout(()=>{this.init(t,n)},0)}}init(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;typeof n=="function"&&(r=n,n={}),!n.defaultNS&&n.defaultNS!==!1&&n.ns&&(typeof n.ns=="string"?n.defaultNS=n.ns:n.ns.indexOf("translation")<0&&(n.defaultNS=n.ns[0]));const i=OE();this.options={...i,...this.options,...RE(n)},this.options.compatibilityAPI!=="v1"&&(this.options.interpolation={...i.interpolation,...this.options.interpolation}),n.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=n.keySeparator),n.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=n.nsSeparator);function o(c){return c?typeof c=="function"?new c:c:null}if(!this.options.isClone){this.modules.logger?qi.init(o(this.modules.logger),this.options):qi.init(null,this.options);let c;this.modules.formatter?c=this.modules.formatter:typeof Intl<"u"&&(c=hae);const d=new PE(this.options);this.store=new TE(this.options.resources,this.options);const f=this.services;f.logger=qi,f.resourceStore=this.store,f.languageUtils=d,f.pluralResolver=new cae(d,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),c&&(!this.options.interpolation.format||this.options.interpolation.format===i.interpolation.format)&&(f.formatter=o(c),f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new dae(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new gae(o(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",function(h){for(var p=arguments.length,m=new Array(p>1?p-1:0),S=1;S1?p-1:0),S=1;S{h.init&&h.init(this)})}if(this.format=this.options.interpolation.format,r||(r=Op),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const c=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);c.length>0&&c[0]!=="dev"&&(this.options.lng=c[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(c=>{this[c]=function(){return t.store[c](...arguments)}}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(c=>{this[c]=function(){return t.store[c](...arguments),t}});const l=Xc(),u=()=>{const c=(d,f)=>{this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),l.resolve(f),r(d,f)};if(this.languages&&this.options.compatibilityAPI!=="v1"&&!this.isInitialized)return c(null,this.t.bind(this));this.changeLanguage(this.options.lng,c)};return this.options.resources||!this.options.initImmediate?u():setTimeout(u,0),l}loadResources(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Op;const i=typeof t=="string"?t:this.language;if(typeof t=="function"&&(r=t),!this.options.resources||this.options.partialBundledLanguages){if(i&&i.toLowerCase()==="cimode")return r();const o=[],s=a=>{if(!a)return;this.services.languageUtils.toResolveHierarchy(a).forEach(u=>{o.indexOf(u)<0&&o.push(u)})};i?s(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(l=>s(l)),this.options.preload&&this.options.preload.forEach(a=>s(a)),this.services.backendConnector.load(o,this.options.ns,a=>{!a&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(a)})}else r(null)}reloadResources(t,n,r){const i=Xc();return t||(t=this.languages),n||(n=this.options.ns),r||(r=Op),this.services.backendConnector.reload(t,n,o=>{i.resolve(),r(o)}),i}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&LM.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!(["cimode","dev"].indexOf(t)>-1))for(let n=0;n-1)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}}changeLanguage(t,n){var r=this;this.isLanguageChangingTo=t;const i=Xc();this.emit("languageChanging",t);const o=l=>{this.language=l,this.languages=this.services.languageUtils.toResolveHierarchy(l),this.resolvedLanguage=void 0,this.setResolvedLanguage(l)},s=(l,u)=>{u?(o(u),this.translator.changeLanguage(u),this.isLanguageChangingTo=void 0,this.emit("languageChanged",u),this.logger.log("languageChanged",u)):this.isLanguageChangingTo=void 0,i.resolve(function(){return r.t(...arguments)}),n&&n(l,function(){return r.t(...arguments)})},a=l=>{!t&&!l&&this.services.languageDetector&&(l=[]);const u=typeof l=="string"?l:this.services.languageUtils.getBestMatchFromCodes(l);u&&(this.language||o(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector&&this.services.languageDetector.cacheUserLanguage&&this.services.languageDetector.cacheUserLanguage(u)),this.loadResources(u,c=>{s(c,u)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(t),i}getFixedT(t,n,r){var i=this;const o=function(s,a){let l;if(typeof a!="object"){for(var u=arguments.length,c=new Array(u>2?u-2:0),d=2;d`${l.keyPrefix}${f}${p}`):h=l.keyPrefix?`${l.keyPrefix}${f}${s}`:s,i.t(h,l)};return typeof t=="string"?o.lng=t:o.lngs=t,o.ns=n,o.keyPrefix=r,o}t(){return this.translator&&this.translator.translate(...arguments)}exists(){return this.translator&&this.translator.exists(...arguments)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],i=this.options?this.options.fallbackLng:!1,o=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const s=(a,l)=>{const u=this.services.backendConnector.state[`${a}|${l}`];return u===-1||u===2};if(n.precheck){const a=n.precheck(this,s);if(a!==void 0)return a}return!!(this.hasResourceBundle(r,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||s(r,t)&&(!i||s(o,t)))}loadNamespaces(t,n){const r=Xc();return this.options.ns?(typeof t=="string"&&(t=[t]),t.forEach(i=>{this.options.ns.indexOf(i)<0&&this.options.ns.push(i)}),this.loadResources(i=>{r.resolve(),n&&n(i)}),r):(n&&n(),Promise.resolve())}loadLanguages(t,n){const r=Xc();typeof t=="string"&&(t=[t]);const i=this.options.preload||[],o=t.filter(s=>i.indexOf(s)<0);return o.length?(this.options.preload=i.concat(o),this.loadResources(s=>{r.resolve(),n&&n(s)}),r):(n&&n(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language)),!t)return"rtl";const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services&&this.services.languageUtils||new PE(OE());return n.indexOf(r.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;return new Lf(t,n)}cloneInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Op;const r=t.forkResourceStore;r&&delete t.forkResourceStore;const i={...this.options,...t,isClone:!0},o=new Lf(i);return(t.debug!==void 0||t.prefix!==void 0)&&(o.logger=o.logger.clone(t)),["store","services","language"].forEach(a=>{o[a]=this[a]}),o.services={...this.services},o.services.utils={hasLoadedNamespace:o.hasLoadedNamespace.bind(o)},r&&(o.store=new TE(this.store.data,i),o.services.resourceStore=o.store),o.translator=new qm(o.services,i),o.translator.on("*",function(a){for(var l=arguments.length,u=new Array(l>1?l-1:0),c=1;ctypeof e=="string"?{title:e,status:"info",isClosable:!0,duration:2500}:{status:"info",isClosable:!0,duration:2500,...e},$M={isConnected:!1,isProcessing:!1,isGFPGANAvailable:!0,isESRGANAvailable:!0,shouldConfirmOnDelete:!0,currentStep:0,totalSteps:0,currentIteration:0,totalIterations:0,currentStatusHasSteps:!1,isCancelable:!0,enableImageDebugging:!1,toastQueue:[],progressImage:null,shouldAntialiasProgressImage:!1,sessionId:null,cancelType:"immediate",isCancelScheduled:!1,subscribedNodeIds:[],wereModelsReceived:!1,wasSchemaParsed:!1,consoleLogLevel:"debug",shouldLogToConsole:!0,statusTranslationKey:"common.statusDisconnected",canceledSession:"",isPersisted:!1,language:"en",isUploading:!1,isNodesEnabled:!1,shouldUseNSFWChecker:!1,shouldUseWatermarker:!1},FM=Pt({name:"system",initialState:$M,reducers:{setIsProcessing:(e,t)=>{e.isProcessing=t.payload},setCurrentStatus:(e,t)=>{e.statusTranslationKey=t.payload},setShouldConfirmOnDelete:(e,t)=>{e.shouldConfirmOnDelete=t.payload},setIsCancelable:(e,t)=>{e.isCancelable=t.payload},setEnableImageDebugging:(e,t)=>{e.enableImageDebugging=t.payload},addToast:(e,t)=>{e.toastQueue.push(t.payload)},clearToastQueue:e=>{e.toastQueue=[]},cancelScheduled:e=>{e.isCancelScheduled=!0},scheduledCancelAborted:e=>{e.isCancelScheduled=!1},cancelTypeChanged:(e,t)=>{e.cancelType=t.payload},subscribedNodeIdsSet:(e,t)=>{e.subscribedNodeIds=t.payload},consoleLogLevelChanged:(e,t)=>{e.consoleLogLevel=t.payload},shouldLogToConsoleChanged:(e,t)=>{e.shouldLogToConsole=t.payload},shouldAntialiasProgressImageChanged:(e,t)=>{e.shouldAntialiasProgressImage=t.payload},isPersistedChanged:(e,t)=>{e.isPersisted=t.payload},languageChanged:(e,t)=>{e.language=t.payload},progressImageSet(e,t){e.progressImage=t.payload},setIsNodesEnabled(e,t){e.isNodesEnabled=t.payload},shouldUseNSFWCheckerChanged(e,t){e.shouldUseNSFWChecker=t.payload},shouldUseWatermarkerChanged(e,t){e.shouldUseWatermarker=t.payload}},extraReducers(e){e.addCase(s7,(t,n)=>{t.sessionId=n.payload.sessionId,t.canceledSession=""}),e.addCase(l7,t=>{t.sessionId=null}),e.addCase(r7,t=>{t.isConnected=!0,t.isCancelable=!0,t.isProcessing=!1,t.currentStatusHasSteps=!1,t.currentStep=0,t.totalSteps=0,t.currentIteration=0,t.totalIterations=0,t.statusTranslationKey="common.statusConnected"}),e.addCase(o7,t=>{t.isConnected=!1,t.isProcessing=!1,t.isCancelable=!0,t.currentStatusHasSteps=!1,t.currentStep=0,t.totalSteps=0,t.statusTranslationKey="common.statusDisconnected"}),e.addCase(c7,t=>{t.isCancelable=!0,t.isProcessing=!0,t.currentStatusHasSteps=!1,t.currentStep=0,t.totalSteps=0,t.statusTranslationKey="common.statusGenerating"}),e.addCase(m7,(t,n)=>{const{step:r,total_steps:i,progress_image:o}=n.payload.data;t.isProcessing=!0,t.isCancelable=!0,t.currentStatusHasSteps=!0,t.currentStep=r+1,t.totalSteps=i,t.progressImage=o??null,t.statusTranslationKey="common.statusGenerating"}),e.addCase(d7,(t,n)=>{const{data:r}=n.payload;t.currentStatusHasSteps=!1,t.currentStep=0,t.totalSteps=0,t.statusTranslationKey="common.statusProcessingComplete",t.canceledSession===r.graph_execution_state_id&&(t.isProcessing=!1,t.isCancelable=!0)}),e.addCase(p7,t=>{t.isProcessing=!1,t.isCancelable=!1,t.isCancelScheduled=!1,t.currentStep=0,t.totalSteps=0,t.statusTranslationKey="common.statusConnected",t.progressImage=null}),e.addCase(Ph,t=>{t.isProcessing=!0,t.isCancelable=!0,t.currentStatusHasSteps=!1,t.statusTranslationKey="common.statusPreparing"}),e.addCase(hl.fulfilled,(t,n)=>{t.canceledSession=n.meta.arg.session_id,t.isProcessing=!1,t.isCancelable=!1,t.isCancelScheduled=!1,t.currentStep=0,t.totalSteps=0,t.statusTranslationKey="common.statusConnected",t.progressImage=null,t.toastQueue.push(Ga({title:kd("toast.canceled"),status:"warning"}))}),e.addCase(dC,t=>{t.wasSchemaParsed=!0}),e.addMatcher(IR,(t,n)=>{var r;t.isProcessing=!1,t.isCancelable=!1,t.isCancelScheduled=!1,t.currentStep=0,t.totalSteps=0,t.statusTranslationKey="common.statusConnected",t.progressImage=null,t.toastQueue.push(Ga({title:kd("toast.serverError"),status:"error",description:((r=n.payload)==null?void 0:r.status)===422?"Validation Error":void 0}))}),e.addMatcher(_ae,(t,n)=>{t.isProcessing=!1,t.isCancelable=!0,t.currentStatusHasSteps=!1,t.currentStep=0,t.totalSteps=0,t.statusTranslationKey="common.statusError",t.progressImage=null,t.toastQueue.push(Ga({title:kd("toast.serverError"),status:"error",description:YX(n.payload.data.error_type)}))})}}),{setIsProcessing:c5e,setShouldConfirmOnDelete:d5e,setCurrentStatus:f5e,setIsCancelable:h5e,setEnableImageDebugging:p5e,addToast:Ft,clearToastQueue:g5e,cancelScheduled:m5e,scheduledCancelAborted:y5e,cancelTypeChanged:v5e,subscribedNodeIdsSet:b5e,consoleLogLevelChanged:S5e,shouldLogToConsoleChanged:_5e,isPersistedChanged:w5e,shouldAntialiasProgressImageChanged:x5e,languageChanged:C5e,progressImageSet:yae,setIsNodesEnabled:T5e,shouldUseNSFWCheckerChanged:vae,shouldUseWatermarkerChanged:bae}=FM.actions,Sae=FM.reducer,_ae=ei(Ux,S7,w7),wae={searchFolder:null,advancedAddScanModel:null},BM=Pt({name:"modelmanager",initialState:wae,reducers:{setSearchFolder:(e,t)=>{e.searchFolder=t.payload},setAdvancedAddScanModel:(e,t)=>{e.advancedAddScanModel=t.payload}}}),{setSearchFolder:E5e,setAdvancedAddScanModel:P5e}=BM.actions,xae=BM.reducer,jM={shift:!1},VM=Pt({name:"hotkeys",initialState:jM,reducers:{shiftKeyPressed:(e,t)=>{e.shift=t.payload}}}),{shiftKeyPressed:A5e}=VM.actions,Cae=VM.reducer,Tae=nF(DV);zM=c2=void 0;var Eae=Tae,Pae=function(){var t=[],n=[],r=void 0,i=function(u){return r=u,function(c){return function(d){return Eae.compose.apply(void 0,n)(c)(d)}}},o=function(){for(var u,c,d=arguments.length,f=Array(d),h=0;h=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(u){throw u},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var o=!0,s=!1,a;return{s:function(){n=n.call(e)},n:function(){var u=n.next();return o=u.done,u},e:function(u){s=!0,a=u},f:function(){try{!o&&n.return!=null&&n.return()}finally{if(s)throw a}}}}function GM(e,t){if(e){if(typeof e=="string")return ME(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return ME(e,t)}}function ME(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0,i=r.prefix,o=r.driver,s=r.persistWholeStore,a=r.serialize;try{var l=s?Vae:zae;yield l(t,n,{prefix:i,driver:o,serialize:a})}catch(u){console.warn("redux-remember: persist error",u)}});return function(){return e.apply(this,arguments)}}();function $E(e,t,n,r,i,o,s){try{var a=e[o](s),l=a.value}catch(u){n(u);return}a.done?t(l):Promise.resolve(l).then(r,i)}function FE(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function s(l){$E(o,r,i,s,a,"next",l)}function a(l){$E(o,r,i,s,a,"throw",l)}s(void 0)})}}var Gae=function(){var e=FE(function*(t,n,r){var i=r.prefix,o=r.driver,s=r.serialize,a=r.unserialize,l=r.persistThrottle,u=r.persistDebounce,c=r.persistWholeStore;yield Lae(t,n,{prefix:i,driver:o,unserialize:a,persistWholeStore:c});var d={},f=function(){var h=FE(function*(){var p=UM(t.getState(),n);yield Uae(p,d,{prefix:i,driver:o,serialize:s,persistWholeStore:c}),pC(p,d)||t.dispatch({type:Rae,payload:p}),d=p});return function(){return h.apply(this,arguments)}}();u&&u>0?t.subscribe(Mae(f,u)):t.subscribe(Iae(f,l))});return function(n,r,i){return e.apply(this,arguments)}}();const Hae=Gae;function $f(e){"@babel/helpers - typeof";return $f=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$f(e)}function BE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function jb(e){for(var t=1;t0&&arguments[0]!==void 0?arguments[0]:n.state,i=arguments.length>1?arguments[1]:void 0;i.type&&(i.type==="@@INIT"||i.type.startsWith("@@redux/INIT"))&&(n.state=jb({},r));var o=typeof t=="function"?t:pc(t);switch(i.type){case d2:return n.state=o(jb(jb({},n.state),i.payload||{}),{type:d2}),n.state;default:return o(r,i)}}},Yae=function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=r.prefix,o=i===void 0?"@@remember-":i,s=r.serialize,a=s===void 0?function(S,v){return JSON.stringify(S)}:s,l=r.unserialize,u=l===void 0?function(S,v){return JSON.parse(S)}:l,c=r.persistThrottle,d=c===void 0?100:c,f=r.persistDebounce,h=r.persistWholeStore,p=h===void 0?!1:h;if(!t)throw Error("redux-remember error: driver required");if(!Array.isArray(n))throw Error("redux-remember error: rememberedKeys needs to be an array");var m=function(v){return function(y,g,b){var _=v(y,g,b);return Hae(_,n,{driver:t,prefix:o,serialize:a,unserialize:u,persistThrottle:d,persistDebounce:f,persistWholeStore:p}),_}};return m};const k5e=["chakra-ui-color-mode","i18nextLng","ROARR_FILTER","ROARR_LOG"],Qae="@@invokeai-",Zae=["cursorPosition","isCanvasInitialized","doesCanvasNeedScaling"],Jae=["pendingControlImages"],ele=["selection","selectedBoardId","galleryView"],tle=["schema","invocationTemplates"],nle=[],rle=[],ile=["currentIteration","currentStep","isCancelable","isConnected","isESRGANAvailable","isGFPGANAvailable","isProcessing","totalIterations","totalSteps","isCancelScheduled","progressImage","wereModelsReceived","wasSchemaParsed","isPersisted","isUploading"],ole=["shouldShowImageDetails"],sle={canvas:Zae,gallery:ele,generation:nle,nodes:tle,postprocessing:rle,system:ile,ui:ole,controlNet:Jae},ale=(e,t)=>{const n=_0(e,sle[t]);return JSON.stringify(n)},lle={canvas:NR,gallery:k7,generation:Wo,nodes:kM,postprocessing:IM,system:$M,config:gR,ui:kR,hotkeys:jM,controlNet:z_},ule=(e,t)=>gX(JSON.parse(e),lle[t]),qM=ue("nodes/textToImageGraphBuilt"),WM=ue("nodes/imageToImageGraphBuilt"),KM=ue("nodes/canvasGraphBuilt"),XM=ue("nodes/nodesGraphBuilt"),cle=ei(qM,WM,KM,XM),dle=e=>{if(cle(e)&&e.payload.nodes){const t={};return{...e,payload:{...e.payload,nodes:t}}}return Df.fulfilled.match(e)?{...e,payload:""}:dC.match(e)?{...e,payload:""}:e},fle=["canvas/setCursorPosition","canvas/setStageCoordinates","canvas/setStageScale","canvas/setIsDrawing","canvas/setBoundingBoxCoordinates","canvas/setBoundingBoxDimensions","canvas/setIsDrawing","canvas/addPointToCurrentLine","socket/socketGeneratorProgress","socket/appSocketGeneratorProgress","hotkeys/shiftKeyPressed","@@REMEMBER_PERSISTED"],hle=e=>e,ple=()=>{le({actionCreator:FQ,effect:async(e,{dispatch:t,getState:n})=>{const r=fe("canvas"),i=n(),{sessionId:o,isProcessing:s}=i.system,a=e.payload;if(s){if(!a){r.debug("No canvas session, skipping cancel");return}if(a!==o){r.debug({canvasSessionId:a,session_id:o},"Canvas session does not match global session, skipping cancel");return}t(hl({session_id:o}))}}})};ue("app/appStarted");const gle=()=>{le({matcher:he.endpoints.listImages.matchFulfilled,effect:async(e,{dispatch:t,unsubscribe:n,cancelActiveListeners:r})=>{if(e.meta.arg.queryCacheKey!==di({board_id:"none",categories:gi}))return;r(),n();const i=e.payload;i.ids.length>0&&t(Rs(i.ids[0]))}})},gC=Hs.injectEndpoints({endpoints:e=>({getAppVersion:e.query({query:()=>({url:"app/version",method:"GET"}),providesTags:["AppVersion"],keepUnusedDataFor:864e5}),getAppConfig:e.query({query:()=>({url:"app/config",method:"GET"}),providesTags:["AppConfig"],keepUnusedDataFor:864e5})})}),{useGetAppVersionQuery:O5e,useGetAppConfigQuery:R5e}=gC,mle=()=>{le({matcher:gC.endpoints.getAppConfig.matchFulfilled,effect:async(e,{getState:t,dispatch:n})=>{const{infill_methods:r,nsfw_methods:i,watermarking_methods:o}=e.payload,s=t().generation.infillMethod;r.includes(s)||n(yQ(r[0])),i.includes("nsfw_checker")||n(vae(!1)),o.includes("invisible_watermark")||n(bae(!1))}})},yle=ue("app/appStarted"),vle=()=>{le({actionCreator:yle,effect:async(e,{unsubscribe:t,cancelActiveListeners:n})=>{n(),t()}})},mC={memoizeOptions:{resultEqualityCheck:S0}},YM=(e,t)=>{var d;const{generation:n,canvas:r,nodes:i,controlNet:o}=e,s=((d=n.initialImage)==null?void 0:d.imageName)===t,a=r.layerState.objects.some(f=>f.kind==="image"&&f.imageName===t),l=i.nodes.some(f=>Ea(f.data.inputs,h=>{var p;return h.type==="image"&&((p=h.value)==null?void 0:p.image_name)===t})),u=Ea(o.controlNets,f=>f.controlImage===t||f.processedControlImage===t);return{isInitialImage:s,isCanvasImage:a,isNodesImage:l,isControlNetImage:u}},ble=Jn([e=>e],e=>{const{imageToDelete:t}=e.imageDeletion;if(!t)return;const{image_name:n}=t;return YM(e,n)},mC),Sle=()=>{le({matcher:ec.endpoints.deleteBoardAndImages.matchFulfilled,effect:async(e,{dispatch:t,getState:n})=>{const{deleted_images:r}=e.payload;let i=!1,o=!1,s=!1,a=!1;const l=n();r.forEach(u=>{const c=YM(l,u);c.isInitialImage&&!i&&(t(ER()),i=!0),c.isCanvasImage&&!o&&(t(LR()),o=!0),c.isNodesImage&&!s&&(t(RM()),s=!0),c.isControlNetImage&&!a&&(t(T7()),a=!0)})}})},_le=()=>{le({matcher:ei(U_,Am),effect:async(e,{getState:t,dispatch:n,condition:r,cancelActiveListeners:i})=>{i();const o=t(),s=U_.match(e)?e.payload:o.gallery.selectedBoardId,l=(Am.match(e)?e.payload:o.gallery.galleryView)==="images"?gi:_s,u={board_id:s??"none",categories:l};if(await r(()=>he.endpoints.listImages.select(u)(t()).isSuccess,5e3)){const{data:d}=he.endpoints.listImages.select(u)(t());d!=null&&d.ids.length?n(Rs(d.ids[0]??null)):n(Rs(null))}else n(Rs(null))}})},wle=ue("canvas/canvasSavedToGallery"),xle=ue("canvas/canvasCopiedToClipboard"),Cle=ue("canvas/canvasDownloadedAsImage"),Tle=ue("canvas/canvasMerged"),Ele=ue("canvas/stagingAreaImageSaved");let QM=null,ZM=null;const I5e=e=>{QM=e},tv=()=>QM,M5e=e=>{ZM=e},Ple=()=>ZM,Ale=async e=>new Promise((t,n)=>{e.toBlob(r=>{if(r){t(r);return}n("Unable to create Blob")})}),Km=async(e,t)=>await Ale(e.toCanvas(t)),yC=async e=>{const t=tv();if(!t)return;const{shouldCropToBoundingBoxOnSave:n,boundingBoxCoordinates:r,boundingBoxDimensions:i}=e.canvas,o=t.clone();o.scale({x:1,y:1});const s=o.getAbsolutePosition(),a=n?{x:r.x+s.x,y:r.y+s.y,width:i.width,height:i.height}:o.getClientRect();return Km(o,a)},kle=e=>{navigator.clipboard.write([new ClipboardItem({[e.type]:e})])},Ole=()=>{le({actionCreator:xle,effect:async(e,{dispatch:t,getState:n})=>{const r=Z0.get().child({namespace:"canvasCopiedToClipboardListener"}),i=n(),o=await yC(i);if(!o){r.error("Problem getting base layer blob"),t(Ft({title:"Problem Copying Canvas",description:"Unable to export base layer",status:"error"}));return}kle(o),t(Ft({title:"Canvas Copied to Clipboard",status:"success"}))}})},Rle=(e,t)=>{const n=URL.createObjectURL(e),r=document.createElement("a");r.href=n,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r),r.remove()},Ile=()=>{le({actionCreator:Cle,effect:async(e,{dispatch:t,getState:n})=>{const r=Z0.get().child({namespace:"canvasSavedToGalleryListener"}),i=n(),o=await yC(i);if(!o){r.error("Problem getting base layer blob"),t(Ft({title:"Problem Downloading Canvas",description:"Unable to export base layer",status:"error"}));return}Rle(o,"canvas.png"),t(Ft({title:"Canvas Downloaded",status:"success"}))}})},Mle=async()=>{const e=tv();if(!e)return;const t=e.clone();return t.scale({x:1,y:1}),Km(t,t.getClientRect())},Nle=()=>{le({actionCreator:Tle,effect:async(e,{dispatch:t})=>{const n=Z0.get().child({namespace:"canvasCopiedToClipboardListener"}),r=await Mle();if(!r){n.error("Problem getting base layer blob"),t(Ft({title:"Problem Merging Canvas",description:"Unable to export base layer",status:"error"}));return}const i=tv();if(!i){n.error("Problem getting canvas base layer"),t(Ft({title:"Problem Merging Canvas",description:"Unable to export base layer",status:"error"}));return}const o=i.getClientRect({relativeTo:i.getParent()}),s=await t(he.endpoints.uploadImage.initiate({file:new File([r],"mergedCanvas.png",{type:"image/png"}),image_category:"general",is_intermediate:!0,postUploadAction:{type:"TOAST",toastOptions:{title:"Canvas Merged"}}})).unwrap(),{image_name:a}=s;t(BQ({kind:"image",layer:"base",imageName:a,...o}))}})},Dle=()=>{le({actionCreator:wle,effect:async(e,{dispatch:t,getState:n})=>{const r=fe("canvas"),i=n(),o=await yC(i);if(!o){r.error("Problem getting base layer blob"),t(Ft({title:"Problem Saving Canvas",description:"Unable to export base layer",status:"error"}));return}t(he.endpoints.uploadImage.initiate({file:new File([o],"savedCanvas.png",{type:"image/png"}),image_category:"general",is_intermediate:!1,board_id:i.gallery.autoAddBoardId,crop_visible:!0,postUploadAction:{type:"TOAST",toastOptions:{title:"Canvas Saved to Gallery"}}}))}})},Lle=(e,t,n)=>{if(!(tJ.match(e)||bT.match(e)||Hx.match(e)||nJ.match(e)||ST.match(e))||ST.match(e)&&n.controlNet.controlNets[e.payload.controlNetId].shouldAutoConfig===!0)return!1;const{controlImage:i,processorType:o,shouldAutoConfig:s}=t.controlNet.controlNets[e.payload.controlNetId];if(bT.match(e)&&!s)return!1;const a=o!=="none",l=t.system.isProcessing;return a&&!l&&!!i},$le=()=>{le({predicate:Lle,effect:async(e,{dispatch:t,cancelActiveListeners:n,delay:r})=>{const i=fe("session"),{controlNetId:o}=e.payload;n(),i.trace("ControlNet auto-process triggered"),await r(300),t(Gx({controlNetId:o}))}})},pl=ue("system/sessionReadyToInvoke"),JM=e=>(e==null?void 0:e.type)==="image_output",Fle=()=>{le({actionCreator:Gx,effect:async(e,{dispatch:t,getState:n,take:r})=>{const i=fe("session"),{controlNetId:o}=e.payload,s=n().controlNet.controlNets[o];if(!s.controlImage){i.error("Unable to process ControlNet image");return}const a={nodes:{[s.processorNode.id]:{...s.processorNode,is_intermediate:!0,image:{image_name:s.controlImage}}}},l=t(On({graph:a})),[u]=await r(f=>On.fulfilled.match(f)&&f.meta.requestId===l.requestId),c=u.payload.id;t(pl());const[d]=await r(f=>zx.match(f)&&f.payload.data.graph_execution_state_id===c);if(JM(d.payload.data.result)){const{image_name:f}=d.payload.data.result.image,[{payload:h}]=await r(m=>he.endpoints.getImageDTO.matchFulfilled(m)&&m.payload.image_name===f),p=h;i.debug({controlNetId:e.payload,processedControlImage:p},"ControlNet image processed"),t(eJ({controlNetId:o,processedControlImage:p.image_name}))}}})},Ble=()=>{le({matcher:he.endpoints.addImageToBoard.matchFulfilled,effect:e=>{const t=fe("images"),{board_id:n,imageDTO:r}=e.meta.arg.originalArgs;t.debug({board_id:n,imageDTO:r},"Image added to board")}})},jle=()=>{le({matcher:he.endpoints.addImageToBoard.matchRejected,effect:e=>{const t=fe("images"),{board_id:n,imageDTO:r}=e.meta.arg.originalArgs;t.debug({board_id:n,imageDTO:r},"Problem adding image to board")}})},N5e=e=>e.gallery,D5e=Jn(e=>e,e=>e.gallery.selection[e.gallery.selection.length-1],mC),Vle=Jn([e=>e],e=>{const{selectedBoardId:t,galleryView:n}=e.gallery;return{board_id:t??"none",categories:n==="images"?gi:_s,offset:0,limit:GQ,is_intermediate:!1}},mC),eN=ue("imageDeletion/imageDeletionConfirmed"),zle=()=>{le({actionCreator:eN,effect:async(e,{dispatch:t,getState:n,condition:r})=>{const{imageDTO:i,imageUsage:o}=e.payload;t(I7(!1));const{image_name:s}=i,a=n();if(a.gallery.selection[a.gallery.selection.length-1]===s){const d=Vle(a),{data:f}=he.endpoints.listImages.select(d)(a),h=(f==null?void 0:f.ids)??[],p=h.findIndex(y=>y.toString()===s),m=h.filter(y=>y.toString()!==s),S=Ss(p,0,m.length-1),v=m[S];t(Rs(v||null))}o.isCanvasImage&&t(LR()),o.isControlNetImage&&t(T7()),o.isInitialImage&&t(ER()),o.isNodesImage&&t(RM());const{requestId:u}=t(he.endpoints.deleteImage.initiate(i));await r(d=>he.endpoints.deleteImage.matchFulfilled(d)&&d.meta.requestId===u,3e4)&&t(Hs.util.invalidateTags([{type:"Board",id:i.board_id}]))}})},Ule=()=>{le({matcher:he.endpoints.deleteImage.matchPending,effect:()=>{}})},Gle=()=>{le({matcher:he.endpoints.deleteImage.matchFulfilled,effect:e=>{fe("images").debug({imageDTO:e.meta.arg.originalArgs},"Image deleted")}})},Hle=()=>{le({matcher:he.endpoints.deleteImage.matchRejected,effect:e=>{fe("images").debug({imageDTO:e.meta.arg.originalArgs},"Unable to delete image")}})},tN=ue("dnd/dndDropped"),qle=()=>{le({actionCreator:tN,effect:async(e,{dispatch:t})=>{const n=fe("images"),{activeData:r,overData:i}=e.payload;if(n.debug({activeData:r,overData:i},"Image or selection dropped"),i.actionType==="SET_CURRENT_IMAGE"&&r.payloadType==="IMAGE_DTO"&&r.payload.imageDTO){t(Rs(r.payload.imageDTO.image_name));return}if(i.actionType==="SET_INITIAL_IMAGE"&&r.payloadType==="IMAGE_DTO"&&r.payload.imageDTO){t(C0(r.payload.imageDTO));return}if(i.actionType==="ADD_TO_BATCH"&&r.payloadType==="IMAGE_DTO"&&r.payload.imageDTO){t(G_([r.payload.imageDTO.image_name]));return}if(i.actionType==="ADD_TO_BATCH"&&r.payloadType==="IMAGE_NAMES"){t(G_(r.payload.image_names));return}if(i.actionType==="SET_CONTROLNET_IMAGE"&&r.payloadType==="IMAGE_DTO"&&r.payload.imageDTO){const{controlNetId:o}=i.context;t(Hx({controlImage:r.payload.imageDTO.image_name,controlNetId:o}));return}if(i.actionType==="SET_CANVAS_INITIAL_IMAGE"&&r.payloadType==="IMAGE_DTO"&&r.payload.imageDTO){t($R(r.payload.imageDTO));return}if(i.actionType==="SET_NODES_IMAGE"&&r.payloadType==="IMAGE_DTO"&&r.payload.imageDTO){const{fieldName:o,nodeId:s}=i.context;t(u2({nodeId:s,fieldName:o,value:r.payload.imageDTO}));return}if(i.actionType==="SET_MULTI_NODES_IMAGE"&&r.payloadType==="IMAGE_DTO"&&r.payload.imageDTO){const{fieldName:o,nodeId:s}=i.context;t(u2({nodeId:s,fieldName:o,value:[r.payload.imageDTO]}));return}if(i.actionType==="MOVE_BOARD"&&r.payloadType==="IMAGE_DTO"&&r.payload.imageDTO){const{imageDTO:o}=r.payload,{boardId:s}=i.context;if(!s){t(he.endpoints.removeImageFromBoard.initiate({imageDTO:o}));return}t(he.endpoints.addImageToBoard.initiate({imageDTO:o,board_id:s}));return}}})},Wle=()=>{le({matcher:he.endpoints.removeImageFromBoard.matchFulfilled,effect:e=>{const t=fe("images"),n=e.meta.arg.originalArgs;t.debug({imageDTO:n},"Image removed from board")}})},Kle=()=>{le({matcher:he.endpoints.removeImageFromBoard.matchRejected,effect:e=>{const t=fe("images"),n=e.meta.arg.originalArgs;t.debug({imageDTO:n},"Problem removing image from board")}})},Xle=()=>{le({actionCreator:dJ,effect:async(e,{dispatch:t,getState:n})=>{const r=e.payload,i=n(),{shouldConfirmOnDelete:o}=i.system,s=ble(n());if(!s)return;const a=s.isCanvasImage||s.isInitialImage||s.isControlNetImage||s.isNodesImage;if(o||a){t(I7(!0));return}t(eN({imageDTO:r,imageUsage:s}))}})},ga={title:"Image Uploaded",status:"success"},Yle=()=>{le({matcher:he.endpoints.uploadImage.matchFulfilled,effect:(e,{dispatch:t,getState:n})=>{const r=fe("images"),i=e.payload,o=n(),{autoAddBoardId:s}=o.gallery;r.debug({imageDTO:i},"Image uploaded");const{postUploadAction:a}=e.meta.arg.originalArgs;if(!(e.payload.is_intermediate&&!a)){if((a==null?void 0:a.type)==="TOAST"){const{toastOptions:l}=a;if(!s)t(Ft({...ga,...l}));else{t(he.endpoints.addImageToBoard.initiate({board_id:s,imageDTO:i}));const{data:u}=ec.endpoints.listAllBoards.select()(o),c=u==null?void 0:u.find(f=>f.board_id===s),d=c?`Added to board ${c.board_name}`:`Added to board ${s}`;t(Ft({...ga,description:d}))}return}if((a==null?void 0:a.type)==="SET_CANVAS_INITIAL_IMAGE"){t($R(i)),t(Ft({...ga,description:"Set as canvas initial image"}));return}if((a==null?void 0:a.type)==="SET_CONTROLNET_IMAGE"){const{controlNetId:l}=a;t(Hx({controlNetId:l,controlImage:i.image_name})),t(Ft({...ga,description:"Set as control image"}));return}if((a==null?void 0:a.type)==="SET_INITIAL_IMAGE"){t(C0(i)),t(Ft({...ga,description:"Set as initial image"}));return}if((a==null?void 0:a.type)==="SET_NODES_IMAGE"){const{nodeId:l,fieldName:u}=a;t(u2({nodeId:l,fieldName:u,value:i})),t(Ft({...ga,description:`Set as node field ${u}`}));return}if((a==null?void 0:a.type)==="ADD_TO_BATCH"){t(G_([i.image_name])),t(Ft({...ga,description:"Added to batch"}));return}}}})},Qle=()=>{le({matcher:he.endpoints.uploadImage.matchRejected,effect:(e,{dispatch:t})=>{const n=fe("images"),r={arg:{..._0(e.meta.arg.originalArgs,["file","postUploadAction"]),file:""}};n.error({...r},"Image upload failed"),t(Ft({title:"Image Upload Failed",description:e.error.message,status:"error"}))}})},Zle=ue("generation/initialImageSelected"),Jle=ue("generation/modelSelected"),eue=()=>{le({actionCreator:Zle,effect:(e,{dispatch:t})=>{if(!e.payload){t(Ft(Ga({title:kd("toast.imageNotLoadedDesc"),status:"error"})));return}t(C0(e.payload)),t(Ft(Ga(kd("toast.sentToImageToImage"))))}})},tue=()=>{le({actionCreator:Jle,effect:(e,{getState:t,dispatch:n})=>{var l;const r=fe("models"),i=t(),o=xf.safeParse(e.payload);if(!o.success){r.error({error:o.error.format()},"Failed to parse main model");return}const s=o.data,{base_model:a}=s;if(((l=i.generation.model)==null?void 0:l.base_model)!==a){let u=0;Qa(i.lora.loras,(f,h)=>{f.base_model!==a&&(n(N7(h)),u+=1)});const{vae:c}=i.generation;c&&c.base_model!==a&&(n(PR(null)),u+=1);const{controlNets:d}=i.controlNet;Qa(d,(f,h)=>{var p;((p=f.model)==null?void 0:p.base_model)!==a&&(n(C7({controlNetId:h})),u+=1)}),u>0&&n(Ft(Ga({title:`Base model changed, cleared ${u} incompatible submodel${u===1?"":"s"}`,status:"warning"})))}n(ja(s))}})},jE=cl({sortComparer:(e,t)=>e.model_name.localeCompare(t.model_name)}),VE=cl({sortComparer:(e,t)=>e.model_name.localeCompare(t.model_name)}),zE=cl({sortComparer:(e,t)=>e.model_name.localeCompare(t.model_name)}),UE=cl({sortComparer:(e,t)=>e.model_name.localeCompare(t.model_name)}),GE=cl({sortComparer:(e,t)=>e.model_name.localeCompare(t.model_name)}),nue=({base_model:e,model_type:t,model_name:n})=>`${e}/${t}/${n}`,Yc=e=>{const t=[];return e.forEach(n=>{const r={...Ln(n),id:nue(n)};t.push(r)}),t},xo=Hs.injectEndpoints({endpoints:e=>({getMainModels:e.query({query:t=>{const n={model_type:"main",base_models:t};return`models/?${F_.stringify(n,{arrayFormat:"none"})}`},providesTags:(t,n,r)=>{const i=[{type:"MainModel",id:Be}];return t&&i.push(...t.ids.map(o=>({type:"MainModel",id:o}))),i},transformResponse:(t,n,r)=>{const i=Yc(t.models);return jE.setAll(jE.getInitialState(),i)}}),updateMainModels:e.mutation({query:({base_model:t,model_name:n,body:r})=>({url:`models/${t}/main/${n}`,method:"PATCH",body:r}),invalidatesTags:[{type:"MainModel",id:Be},{type:"SDXLRefinerModel",id:Be}]}),importMainModels:e.mutation({query:({body:t})=>({url:"models/import",method:"POST",body:t}),invalidatesTags:[{type:"MainModel",id:Be},{type:"SDXLRefinerModel",id:Be}]}),addMainModels:e.mutation({query:({body:t})=>({url:"models/add",method:"POST",body:t}),invalidatesTags:[{type:"MainModel",id:Be},{type:"SDXLRefinerModel",id:Be}]}),deleteMainModels:e.mutation({query:({base_model:t,model_name:n})=>({url:`models/${t}/main/${n}`,method:"DELETE"}),invalidatesTags:[{type:"MainModel",id:Be},{type:"SDXLRefinerModel",id:Be}]}),convertMainModels:e.mutation({query:({base_model:t,model_name:n,params:r})=>({url:`models/convert/${t}/main/${n}`,method:"PUT",params:r}),invalidatesTags:[{type:"MainModel",id:Be},{type:"SDXLRefinerModel",id:Be}]}),mergeMainModels:e.mutation({query:({base_model:t,body:n})=>({url:`models/merge/${t}`,method:"PUT",body:n}),invalidatesTags:[{type:"MainModel",id:Be},{type:"SDXLRefinerModel",id:Be}]}),syncModels:e.mutation({query:()=>({url:"models/sync",method:"POST"}),invalidatesTags:[{type:"MainModel",id:Be},{type:"SDXLRefinerModel",id:Be}]}),getLoRAModels:e.query({query:()=>({url:"models/",params:{model_type:"lora"}}),providesTags:(t,n,r)=>{const i=[{type:"LoRAModel",id:Be}];return t&&i.push(...t.ids.map(o=>({type:"LoRAModel",id:o}))),i},transformResponse:(t,n,r)=>{const i=Yc(t.models);return VE.setAll(VE.getInitialState(),i)}}),getControlNetModels:e.query({query:()=>({url:"models/",params:{model_type:"controlnet"}}),providesTags:(t,n,r)=>{const i=[{type:"ControlNetModel",id:Be}];return t&&i.push(...t.ids.map(o=>({type:"ControlNetModel",id:o}))),i},transformResponse:(t,n,r)=>{const i=Yc(t.models);return zE.setAll(zE.getInitialState(),i)}}),getVaeModels:e.query({query:()=>({url:"models/",params:{model_type:"vae"}}),providesTags:(t,n,r)=>{const i=[{type:"VaeModel",id:Be}];return t&&i.push(...t.ids.map(o=>({type:"VaeModel",id:o}))),i},transformResponse:(t,n,r)=>{const i=Yc(t.models);return GE.setAll(GE.getInitialState(),i)}}),getTextualInversionModels:e.query({query:()=>({url:"models/",params:{model_type:"embedding"}}),providesTags:(t,n,r)=>{const i=[{type:"TextualInversionModel",id:Be}];return t&&i.push(...t.ids.map(o=>({type:"TextualInversionModel",id:o}))),i},transformResponse:(t,n,r)=>{const i=Yc(t.models);return UE.setAll(UE.getInitialState(),i)}}),getModelsInFolder:e.query({query:t=>({url:`/models/search?${F_.stringify(t,{})}`}),providesTags:(t,n,r)=>{const i=[{type:"ScannedModels",id:Be}];return t&&i.push(...t.map(o=>({type:"ScannedModels",id:o}))),i}}),getCheckpointConfigs:e.query({query:()=>({url:"/models/ckpt_confs"})})})}),{useGetMainModelsQuery:L5e,useGetControlNetModelsQuery:$5e,useGetLoRAModelsQuery:F5e,useGetTextualInversionModelsQuery:B5e,useGetVaeModelsQuery:j5e,useUpdateMainModelsMutation:V5e,useDeleteMainModelsMutation:z5e,useImportMainModelsMutation:U5e,useAddMainModelsMutation:G5e,useConvertMainModelsMutation:H5e,useMergeMainModelsMutation:q5e,useSyncModelsMutation:W5e,useGetModelsInFolderQuery:K5e,useGetCheckpointConfigsQuery:X5e}=xo,rue=()=>{le({predicate:(e,t)=>xo.endpoints.getMainModels.matchFulfilled(t)&&!t.meta.arg.originalArgs.includes("sdxl-refiner"),effect:async(e,{getState:t,dispatch:n})=>{const r=fe("models");r.info({models:e.payload.entities},`Main models loaded (${e.payload.ids.length})`);const i=t().generation.model;if(Ea(e.payload.entities,u=>(u==null?void 0:u.model_name)===(i==null?void 0:i.model_name)&&(u==null?void 0:u.base_model)===(i==null?void 0:i.base_model)))return;const s=e.payload.ids[0],a=e.payload.entities[s];if(!a){n(ja(null));return}const l=xf.safeParse(a);if(!l.success){r.error({error:l.error.format()},"Failed to parse main model");return}n(ja(l.data))}}),le({predicate:(e,t)=>xo.endpoints.getMainModels.matchFulfilled(t)&&t.meta.arg.originalArgs.includes("sdxl-refiner"),effect:async(e,{getState:t,dispatch:n})=>{const r=fe("models");r.info({models:e.payload.entities},`SDXL Refiner models loaded (${e.payload.ids.length})`);const i=t().sdxl.refinerModel;if(Ea(e.payload.entities,u=>(u==null?void 0:u.model_name)===(i==null?void 0:i.model_name)&&(u==null?void 0:u.base_model)===(i==null?void 0:i.base_model)))return;const s=e.payload.ids[0],a=e.payload.entities[s];if(!a){n(wE(null)),n(Xse(!1));return}const l=xf.safeParse(a);if(!l.success){r.error({error:l.error.format()},"Failed to parse SDXL Refiner Model");return}n(wE(l.data))}}),le({matcher:xo.endpoints.getVaeModels.matchFulfilled,effect:async(e,{getState:t,dispatch:n})=>{const r=fe("models");r.info({models:e.payload.entities},`VAEs loaded (${e.payload.ids.length})`);const i=t().generation.vae;if(i===null||Ea(e.payload.entities,u=>(u==null?void 0:u.model_name)===(i==null?void 0:i.model_name)&&(u==null?void 0:u.base_model)===(i==null?void 0:i.base_model)))return;const s=e.payload.ids[0],a=e.payload.entities[s];if(!a){n(ja(null));return}const l=pQ.safeParse(a);if(!l.success){r.error({error:l.error.format()},"Failed to parse VAE model");return}n(PR(l.data))}}),le({matcher:xo.endpoints.getLoRAModels.matchFulfilled,effect:async(e,{getState:t,dispatch:n})=>{fe("models").info({models:e.payload.entities},`LoRAs loaded (${e.payload.ids.length})`);const i=t().lora.loras;Qa(i,(o,s)=>{Ea(e.payload.entities,l=>(l==null?void 0:l.model_name)===(o==null?void 0:o.model_name)&&(l==null?void 0:l.base_model)===(o==null?void 0:o.base_model))||n(N7(s))})}}),le({matcher:xo.endpoints.getControlNetModels.matchFulfilled,effect:async(e,{getState:t,dispatch:n})=>{fe("models").info({models:e.payload.entities},`ControlNet models loaded (${e.payload.ids.length})`);const i=t().controlNet.controlNets;Qa(i,(o,s)=>{Ea(e.payload.entities,l=>{var u,c;return(l==null?void 0:l.model_name)===((u=o==null?void 0:o.model)==null?void 0:u.model_name)&&(l==null?void 0:l.base_model)===((c=o==null?void 0:o.model)==null?void 0:c.base_model)})||n(C7({controlNetId:s}))})}}),le({matcher:xo.endpoints.getTextualInversionModels.matchFulfilled,effect:async e=>{fe("models").info({models:e.payload.entities},`Embeddings loaded (${e.payload.ids.length})`)}})},ra=e=>JSON.parse(JSON.stringify(e)),h2=e=>!("$ref"in e),iue=e=>!("$ref"in e),Y5e=500,oue={integer:"integer",float:"float",number:"float",string:"string",boolean:"boolean",enum:"enum",ImageField:"image",image_collection:"image_collection",LatentsField:"latents",ConditioningField:"conditioning",UNetField:"unet",ClipField:"clip",VaeField:"vae",model:"model",refiner_model:"refiner_model",vae_model:"vae_model",lora_model:"lora_model",controlnet_model:"controlnet_model",ControlNetModelField:"controlnet_model",array:"array",item:"item",ColorField:"color",ControlField:"control",control:"control",cfg_scale:"float",control_weight:"float"},sue=500,Dt=e=>`var(--invokeai-colors-${e}-${sue})`,Q5e={integer:{color:"red",colorCssVar:Dt("red"),title:"Integer",description:"Integers are whole numbers, without a decimal point."},float:{color:"orange",colorCssVar:Dt("orange"),title:"Float",description:"Floats are numbers with a decimal point."},string:{color:"yellow",colorCssVar:Dt("yellow"),title:"String",description:"Strings are text."},boolean:{color:"green",colorCssVar:Dt("green"),title:"Boolean",description:"Booleans are true or false."},enum:{color:"blue",colorCssVar:Dt("blue"),title:"Enum",description:"Enums are values that may be one of a number of options."},image:{color:"purple",colorCssVar:Dt("purple"),title:"Image",description:"Images may be passed between nodes."},image_collection:{color:"purple",colorCssVar:Dt("purple"),title:"Image Collection",description:"A collection of images."},latents:{color:"pink",colorCssVar:Dt("pink"),title:"Latents",description:"Latents may be passed between nodes."},conditioning:{color:"cyan",colorCssVar:Dt("cyan"),title:"Conditioning",description:"Conditioning may be passed between nodes."},unet:{color:"red",colorCssVar:Dt("red"),title:"UNet",description:"UNet submodel."},clip:{color:"green",colorCssVar:Dt("green"),title:"Clip",description:"Tokenizer and text_encoder submodels."},vae:{color:"blue",colorCssVar:Dt("blue"),title:"Vae",description:"Vae submodel."},control:{color:"cyan",colorCssVar:Dt("cyan"),title:"Control",description:"Control info passed between nodes."},model:{color:"teal",colorCssVar:Dt("teal"),title:"Model",description:"Models are models."},refiner_model:{color:"teal",colorCssVar:Dt("teal"),title:"Refiner Model",description:"Models are models."},vae_model:{color:"teal",colorCssVar:Dt("teal"),title:"VAE",description:"Models are models."},lora_model:{color:"teal",colorCssVar:Dt("teal"),title:"LoRA",description:"Models are models."},controlnet_model:{color:"teal",colorCssVar:Dt("teal"),title:"ControlNet",description:"Models are models."},array:{color:"gray",colorCssVar:Dt("gray"),title:"Array",description:"TODO: Array type description."},item:{color:"gray",colorCssVar:Dt("gray"),title:"Collection Item",description:"TODO: Collection Item type description."},color:{color:"gray",colorCssVar:Dt("gray"),title:"Color",description:"A RGBA color."}},Z5e=250,Vb=e=>e.$ref.split("/").slice(-1)[0],aue=({schemaObject:e,baseField:t})=>{const n={...t,type:"integer",inputRequirement:"always",inputKind:"any",default:e.default??0};return e.multipleOf!==void 0&&(n.multipleOf=e.multipleOf),e.maximum!==void 0&&(n.maximum=e.maximum),e.exclusiveMaximum!==void 0&&(n.exclusiveMaximum=e.exclusiveMaximum),e.minimum!==void 0&&(n.minimum=e.minimum),e.exclusiveMinimum!==void 0&&(n.exclusiveMinimum=e.exclusiveMinimum),n},lue=({schemaObject:e,baseField:t})=>{const n={...t,type:"float",inputRequirement:"always",inputKind:"any",default:e.default??0};return e.multipleOf!==void 0&&(n.multipleOf=e.multipleOf),e.maximum!==void 0&&(n.maximum=e.maximum),e.exclusiveMaximum!==void 0&&(n.exclusiveMaximum=e.exclusiveMaximum),e.minimum!==void 0&&(n.minimum=e.minimum),e.exclusiveMinimum!==void 0&&(n.exclusiveMinimum=e.exclusiveMinimum),n},uue=({schemaObject:e,baseField:t})=>{const n={...t,type:"string",inputRequirement:"always",inputKind:"any",default:e.default??""};return e.minLength!==void 0&&(n.minLength=e.minLength),e.maxLength!==void 0&&(n.maxLength=e.maxLength),e.pattern!==void 0&&(n.pattern=e.pattern),n},cue=({schemaObject:e,baseField:t})=>({...t,type:"boolean",inputRequirement:"always",inputKind:"any",default:e.default??!1}),due=({schemaObject:e,baseField:t})=>({...t,type:"model",inputRequirement:"always",inputKind:"direct",default:e.default??void 0}),fue=({schemaObject:e,baseField:t})=>({...t,type:"refiner_model",inputRequirement:"always",inputKind:"direct",default:e.default??void 0}),hue=({schemaObject:e,baseField:t})=>({...t,type:"vae_model",inputRequirement:"always",inputKind:"direct",default:e.default??void 0}),pue=({schemaObject:e,baseField:t})=>({...t,type:"lora_model",inputRequirement:"always",inputKind:"direct",default:e.default??void 0}),gue=({schemaObject:e,baseField:t})=>({...t,type:"controlnet_model",inputRequirement:"always",inputKind:"direct",default:e.default??void 0}),mue=({schemaObject:e,baseField:t})=>({...t,type:"image",inputRequirement:"always",inputKind:"any",default:e.default??void 0}),yue=({schemaObject:e,baseField:t})=>({...t,type:"image_collection",inputRequirement:"always",inputKind:"any",default:e.default??void 0}),vue=({schemaObject:e,baseField:t})=>({...t,type:"latents",inputRequirement:"always",inputKind:"connection",default:e.default??void 0}),bue=({schemaObject:e,baseField:t})=>({...t,type:"conditioning",inputRequirement:"always",inputKind:"connection",default:e.default??void 0}),Sue=({schemaObject:e,baseField:t})=>({...t,type:"unet",inputRequirement:"always",inputKind:"connection",default:e.default??void 0}),_ue=({schemaObject:e,baseField:t})=>({...t,type:"clip",inputRequirement:"always",inputKind:"connection",default:e.default??void 0}),wue=({schemaObject:e,baseField:t})=>({...t,type:"vae",inputRequirement:"always",inputKind:"connection",default:e.default??void 0}),xue=({schemaObject:e,baseField:t})=>({...t,type:"control",inputRequirement:"always",inputKind:"connection",default:e.default??void 0}),Cue=({schemaObject:e,baseField:t})=>{const n=e.enum??[];return{...t,type:"enum",enumType:e.type??"string",options:n,inputRequirement:"always",inputKind:"direct",default:e.default??n[0]}},HE=({baseField:e})=>({...e,type:"array",inputRequirement:"always",inputKind:"direct",default:[]}),qE=({baseField:e})=>({...e,type:"item",inputRequirement:"always",inputKind:"direct",default:void 0}),Tue=({schemaObject:e,baseField:t})=>({...t,type:"color",inputRequirement:"always",inputKind:"direct",default:e.default??{r:127,g:127,b:127,a:255}}),nN=(e,t,n)=>{let r="";n&&t in n?r=n[t]:e.type?e.enum?r="enum":e.type&&(r=e.type):e.allOf?r=Vb(e.allOf[0]):e.anyOf?r=Vb(e.anyOf[0]):e.oneOf&&(r=Vb(e.oneOf[0]));const i=oue[r];if(!i)throw`Field type "${r}" is unknown!`;return i},Eue=(e,t,n)=>{const r=nN(e,t,n),i={name:t,title:e.title??"",description:e.description??""};if(["image"].includes(r))return mue({schemaObject:e,baseField:i});if(["image_collection"].includes(r))return yue({schemaObject:e,baseField:i});if(["latents"].includes(r))return vue({schemaObject:e,baseField:i});if(["conditioning"].includes(r))return bue({schemaObject:e,baseField:i});if(["unet"].includes(r))return Sue({schemaObject:e,baseField:i});if(["clip"].includes(r))return _ue({schemaObject:e,baseField:i});if(["vae"].includes(r))return wue({schemaObject:e,baseField:i});if(["control"].includes(r))return xue({schemaObject:e,baseField:i});if(["model"].includes(r))return due({schemaObject:e,baseField:i});if(["refiner_model"].includes(r))return fue({schemaObject:e,baseField:i});if(["vae_model"].includes(r))return hue({schemaObject:e,baseField:i});if(["lora_model"].includes(r))return pue({schemaObject:e,baseField:i});if(["controlnet_model"].includes(r))return gue({schemaObject:e,baseField:i});if(["enum"].includes(r))return Cue({schemaObject:e,baseField:i});if(["integer"].includes(r))return aue({schemaObject:e,baseField:i});if(["number","float"].includes(r))return lue({schemaObject:e,baseField:i});if(["string"].includes(r))return uue({schemaObject:e,baseField:i});if(["boolean"].includes(r))return cue({schemaObject:e,baseField:i});if(["array"].includes(r))return HE({schemaObject:e,baseField:i});if(["item"].includes(r))return qE({schemaObject:e,baseField:i});if(["color"].includes(r))return Tue({schemaObject:e,baseField:i});if(["array"].includes(r))return HE({schemaObject:e,baseField:i});if(["item"].includes(r))return qE({schemaObject:e,baseField:i})},Pue=(e,t,n)=>{const r=e.$ref.split("/").slice(-1)[0],i=t.components.schemas[r];return h2(i)?Lx(i.properties,(s,a,l)=>{if(!["type","id"].includes(l)&&!["object"].includes(a.type)&&h2(a)){const u=nN(a,l,n);s[l]={name:l,title:a.title??"",description:a.description??"",type:u}}return s},{}):{}},Aue=e=>e==="l2i"?["id","type","metadata"]:["id","type","is_intermediate","metadata"],kue=["Graph","InvocationMeta","MetadataAccumulatorInvocation"],Oue=e=>{var r;return oR((r=e.components)==null?void 0:r.schemas,(i,o)=>o.includes("Invocation")&&!o.includes("InvocationOutput")&&!kue.some(s=>o.includes(s))).reduce((i,o)=>{var s,a,l,u,c;if(iue(o)){const d=o.properties.type.default,f=Aue(d),h=((s=o.ui)==null?void 0:s.title)??o.title.replace("Invocation",""),p=(a=o.ui)==null?void 0:a.type_hints,m={};if(d==="collect"){const g=o.properties.item;m.item={type:"item",name:"item",description:g.description??"",title:"Collection Item",inputKind:"connection",inputRequirement:"always",default:void 0}}else if(d==="iterate"){const g=o.properties.collection;m.collection={type:"array",name:"collection",title:g.title??"",default:[],description:g.description??"",inputRequirement:"always",inputKind:"connection"}}else Lx(o.properties,(g,b,_)=>{if(!f.includes(_)&&h2(b)){const w=Eue(b,_,p);w&&(g[_]=w)}return g},m);const S=o.output;let v;if(d==="iterate"){const g=(u=(l=e.components)==null?void 0:l.schemas)==null?void 0:u.IterateInvocationOutput;v={item:{name:"item",title:(g==null?void 0:g.title)??"",description:(g==null?void 0:g.description)??"",type:"array"}}}else v=Pue(S,e,p);const y={title:h,type:d,tags:((c=o.ui)==null?void 0:c.tags)??[],description:o.description??"",inputs:m,outputs:v};Object.assign(i,{[d]:y})}return i},{})},Rue=()=>{le({actionCreator:Df.fulfilled,effect:(e,{dispatch:t})=>{const n=fe("system"),r=e.payload;n.debug({schemaJSON:r},"Dereferenced OpenAPI schema");const i=Oue(r);n.debug({nodeTemplates:ra(i)},`Built ${hR(i)} node templates`),t(dC(i))}}),le({actionCreator:Df.rejected,effect:()=>{fe("system").error("Problem dereferencing OpenAPI Schema")}})},Iue=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,globalThis.DOMException,globalThis.AssertionError,globalThis.SystemError].filter(Boolean).map(e=>[e.name,e]),Mue=new Map(Iue),Nue=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],p2=Symbol(".toJSON was called"),Due=e=>{e[p2]=!0;const t=e.toJSON();return delete e[p2],t},Lue=e=>Mue.get(e)??Error,rN=({from:e,seen:t,to:n,forceEnumerable:r,maxDepth:i,depth:o,useToJSON:s,serialize:a})=>{if(!n)if(Array.isArray(e))n=[];else if(!a&&WE(e)){const u=Lue(e.name);n=new u}else n={};if(t.push(e),o>=i)return n;if(s&&typeof e.toJSON=="function"&&e[p2]!==!0)return Due(e);const l=u=>rN({from:u,seen:[...t],forceEnumerable:r,maxDepth:i,depth:o,useToJSON:s,serialize:a});for(const[u,c]of Object.entries(e)){if(typeof Buffer=="function"&&Buffer.isBuffer(c)){n[u]="[object Buffer]";continue}if(c!==null&&typeof c=="object"&&typeof c.pipe=="function"){n[u]="[object Stream]";continue}if(typeof c!="function"){if(!c||typeof c!="object"){n[u]=c;continue}if(!t.includes(e[u])){o++,n[u]=l(e[u]);continue}n[u]="[Circular]"}}for(const{property:u,enumerable:c}of Nue)typeof e[u]<"u"&&e[u]!==null&&Object.defineProperty(n,u,{value:WE(e[u])?l(e[u]):e[u],enumerable:r?!0:c,configurable:!0,writable:!0});return n};function vC(e,t={}){const{maxDepth:n=Number.POSITIVE_INFINITY,useToJSON:r=!0}=t;return typeof e=="object"&&e!==null?rN({from:e,seen:[],forceEnumerable:!0,maxDepth:n,depth:0,useToJSON:r,serialize:!0}):typeof e=="function"?`[Function: ${e.name??"anonymous"}]`:e}function WE(e){return!!e&&typeof e=="object"&&"name"in e&&"message"in e&&"stack"in e}const $ue=()=>{le({actionCreator:hl.pending,effect:()=>{}})},Fue=()=>{le({actionCreator:hl.fulfilled,effect:e=>{const t=fe("session"),{session_id:n}=e.meta.arg;t.debug({session_id:n},`Session canceled (${n})`)}})},Bue=()=>{le({actionCreator:hl.rejected,effect:e=>{const t=fe("session"),{session_id:n}=e.meta.arg;if(e.payload){const{error:r}=e.payload;t.error({session_id:n,error:vC(r)},"Problem canceling session")}}})},jue=()=>{le({actionCreator:On.pending,effect:()=>{}})},Vue=()=>{le({actionCreator:On.fulfilled,effect:e=>{const t=fe("session"),n=e.payload;t.debug({session:ra(n)},`Session created (${n.id})`)}})},zue=()=>{le({actionCreator:On.rejected,effect:e=>{const t=fe("session");if(e.payload){const{error:n,status:r}=e.payload,i=ra(e.meta.arg);t.error({graph:i,status:r,error:vC(n)},"Problem creating session")}}})},Uue=()=>{le({actionCreator:yh.pending,effect:()=>{}})},Gue=()=>{le({actionCreator:yh.fulfilled,effect:e=>{const t=fe("session"),{session_id:n}=e.meta.arg;t.debug({session_id:n},`Session invoked (${n})`)}})},Hue=()=>{le({actionCreator:yh.rejected,effect:e=>{const t=fe("session"),{session_id:n}=e.meta.arg;if(e.payload){const{error:r}=e.payload;t.error({session_id:n,error:vC(r)},"Problem invoking session")}}})},que=()=>{le({actionCreator:pl,effect:(e,{getState:t,dispatch:n})=>{const r=fe("session"),{sessionId:i}=t().system;i&&(r.debug({session_id:i},`Session ready to invoke (${i})})`),n(yh({session_id:i})))}})},Wue=()=>{le({actionCreator:n7,effect:(e,{dispatch:t,getState:n})=>{fe("socketio").debug("Connected");const{nodes:i,config:o}=n(),{disabledTabs:s}=o;!i.schema&&!s.includes("nodes")&&t(Df()),t(r7(e.payload)),t(xo.util.invalidateTags([{type:"MainModel",id:Be},{type:"SDXLRefinerModel",id:Be},{type:"LoRAModel",id:Be},{type:"ControlNetModel",id:Be},{type:"VaeModel",id:Be},{type:"TextualInversionModel",id:Be},{type:"ScannedModels",id:Be}])),t(gC.util.invalidateTags(["AppConfig","AppVersion"]))}})},Kue=()=>{le({actionCreator:i7,effect:(e,{dispatch:t})=>{fe("socketio").debug("Disconnected"),t(o7(e.payload))}})},Xue=()=>{le({actionCreator:g7,effect:(e,{dispatch:t,getState:n})=>{const r=fe("socketio");if(n().system.canceledSession===e.payload.data.graph_execution_state_id){r.trace(e.payload,"Ignored generator progress for canceled session");return}r.trace(e.payload,`Generator progress (${e.payload.data.node.type})`),t(m7(e.payload))}})},Yue=()=>{le({actionCreator:h7,effect:(e,{dispatch:t})=>{fe("socketio").debug(e.payload,"Session complete"),t(p7(e.payload))}})},Que=["dataURL_image"],Zue=()=>{le({actionCreator:zx,effect:async(e,{dispatch:t,getState:n})=>{const r=fe("socketio"),{data:i}=e.payload;r.debug({data:ra(i)},`Invocation complete (${e.payload.data.node.type})`);const o=e.payload.data.graph_execution_state_id,{cancelType:s,isCancelScheduled:a}=n().system;s==="scheduled"&&a&&t(hl({session_id:o}));const{result:l,node:u,graph_execution_state_id:c}=i;if(JM(l)&&!Que.includes(u.type)){const{image_name:d}=l.image,{canvas:f,gallery:h}=n(),p=await t(he.endpoints.getImageDTO.initiate(d)).unwrap();if(c===f.layerState.stagingArea.sessionId&&t($Q(p)),!p.is_intermediate){const{autoAddBoardId:m}=h;t(m?he.endpoints.addImageToBoard.initiate({board_id:m,imageDTO:p}):he.util.updateQueryData("listImages",{board_id:"none",categories:gi},y=>{const g=y.total,_=Kn.addOne(y,p).total-g;y.total=y.total+_})),t(he.util.invalidateTags([{type:"BoardImagesTotal",id:m??"none"},{type:"BoardAssetsTotal",id:m??"none"}]));const{selectedBoardId:S,shouldAutoSwitch:v}=h;v&&(m&&m!==S?(t(U_(m)),t(Am("images"))):m||t(Am("images")),t(Rs(p.image_name)))}t(yae(null))}t(d7(e.payload))}})},Jue=()=>{le({actionCreator:f7,effect:(e,{dispatch:t})=>{fe("socketio").error(e.payload,`Invocation error (${e.payload.data.node.type})`),t(Ux(e.payload))}})},ece=()=>{le({actionCreator:_7,effect:(e,{dispatch:t})=>{fe("socketio").error(e.payload,`Invocation retrieval error (${e.payload.data.graph_execution_state_id})`),t(w7(e.payload))}})},tce=()=>{le({actionCreator:u7,effect:(e,{dispatch:t,getState:n})=>{const r=fe("socketio");if(n().system.canceledSession===e.payload.data.graph_execution_state_id){r.trace(e.payload,"Ignored invocation started for canceled session");return}r.debug(e.payload,`Invocation started (${e.payload.data.node.type})`),t(c7(e.payload))}})},nce=()=>{le({actionCreator:y7,effect:(e,{dispatch:t})=>{const n=fe("socketio"),{base_model:r,model_name:i,model_type:o,submodel:s}=e.payload.data;let a=`Model load started: ${r}/${o}/${i}`;s&&(a=a.concat(`/${s}`)),n.debug(e.payload,a),t(ZZ(e.payload))}}),le({actionCreator:v7,effect:(e,{dispatch:t})=>{const n=fe("socketio"),{base_model:r,model_name:i,model_type:o,submodel:s}=e.payload.data;let a=`Model load complete: ${r}/${o}/${i}`;s&&(a=a.concat(`/${s}`)),n.debug(e.payload,a),t(JZ(e.payload))}})},rce=()=>{le({actionCreator:b7,effect:(e,{dispatch:t})=>{fe("socketio").error(e.payload,`Session retrieval error (${e.payload.data.graph_execution_state_id})`),t(S7(e.payload))}})},ice=()=>{le({actionCreator:Vx,effect:(e,{dispatch:t})=>{fe("socketio").debug(e.payload,"Subscribed"),t(s7(e.payload))}})},oce=()=>{le({actionCreator:a7,effect:(e,{dispatch:t})=>{fe("socketio").debug(e.payload,"Unsubscribed"),t(l7(e.payload))}})},sce=()=>{le({actionCreator:Ele,effect:async(e,{dispatch:t,getState:n})=>{const{imageDTO:r}=e.payload;try{const i=await t(he.endpoints.changeImageIsIntermediate.initiate({imageDTO:r,is_intermediate:!1})).unwrap(),{autoAddBoardId:o}=n().gallery;o&&await t(he.endpoints.addImageToBoard.initiate({imageDTO:i,board_id:o})),t(Ft({title:"Image Saved",status:"success"}))}catch(i){t(Ft({title:"Image Saving Failed",description:i==null?void 0:i.message,status:"error"}))}}})},J5e=["sd-1","sd-2","sdxl","sdxl-refiner"],ace=["sd-1","sd-2","sdxl"],e4e=["sdxl-refiner"],lce=()=>{le({actionCreator:RR,effect:(e,{getState:t,dispatch:n})=>{if(e.payload==="unifiedCanvas"){const{data:i}=xo.endpoints.getMainModels.select(ace)(t());if(!i){n(ja(null));return}const o=[];Qa(i.entities,u=>{u&&["sd-1","sd-2"].includes(u.base_model)&&o.push(u)});const s=o[0];if(!s){n(ja(null));return}const{base_model:a,model_name:l}=s;n(ja({base_model:a,model_name:l}))}}})},Fe="positive_conditioning",qe="negative_conditioning",dn="text_to_latents",nt="latents_to_image",fu="nsfw_checker",Qc="invisible_watermark",Le="noise",Fi="rand_int",Co="range_of_size",lr="iterate",pt="main_model_loader",Zc="vae_loader",uce="lora_loader",rt="clip_skip",bt="image_to_latents",Kt="latents_to_latents",Qn="resize_image",Mi="inpaint",Rp="control_net_collect",zb="dynamic_prompt",lt="metadata_accumulator",KE="esrgan",en="sdxl_model_loader",is="t2l_sdxl",Ni="l2l_sdxl",zl="sdxl_refiner_model_loader",Ip="sdxl_refiner_positive_conditioning",Mp="sdxl_refiner_negative_conditioning",ma="l2l_sdxl_refiner",bC="text_to_image_graph",cce="sdxl_text_to_image_graph",dce="sxdl_image_to_image_graph",Xm="image_to_image_graph",iN="inpaint_graph",fce=({image_name:e,esrganModelName:t})=>{const n={id:KE,type:"esrgan",image:{image_name:e},model_name:t,is_intermediate:!1};return{id:"adhoc-esrgan-graph",nodes:{[KE]:n},edges:[]}},hce=ue("upscale/upscaleRequested"),pce=()=>{le({actionCreator:hce,effect:async(e,{dispatch:t,getState:n,take:r})=>{const{image_name:i}=e.payload,{esrganModelName:o}=n().postprocessing,s=fce({image_name:i,esrganModelName:o});t(On({graph:s})),await r(On.fulfilled.match),t(pl())}})},gce=e=>{const t=window.open("");t&&e.forEach(n=>{const r=new Image;r.src=n.base64,t.document.write(n.caption),t.document.write("
"),t.document.write(r.outerHTML),t.document.write("

")})},XE=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=i=>t(r.result),r.onerror=i=>n(r.error),r.onabort=i=>n(new Error("Read aborted")),r.readAsDataURL(e)});var SC={exports:{}},nv={},oN={},Pe={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e._registerNode=e.Konva=e.glob=void 0;var t=Math.PI/180;function n(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}e.glob=typeof Ee<"u"?Ee:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},e.Konva={_global:e.glob,version:"9.2.0",isBrowser:n(),isUnminified:/param/.test((function(i){}).toString()),dblClickWindow:400,getAngle(i){return e.Konva.angleDeg?i*t:i},enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_mouseListenClick:!1,_touchListenClick:!1,_pointerListenClick:!1,_mouseInDblClickWindow:!1,_touchInDblClickWindow:!1,_pointerInDblClickWindow:!1,_mouseDblClickPointerId:null,_touchDblClickPointerId:null,_pointerDblClickPointerId:null,pixelRatio:typeof window<"u"&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging(){return e.Konva.DD.isDragging},isDragReady(){return!!e.Konva.DD.node},releaseCanvasOnDestroy:!0,document:e.glob.document,_injectGlobal(i){e.glob.Konva=i}};const r=i=>{e.Konva[i.prototype.getClassName()]=i};e._registerNode=r,e.Konva._injectGlobal(e.Konva)})(Pe);var Rt={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Util=e.Transform=void 0;const t=Pe;class n{constructor(b=[1,0,0,1,0,0]){this.dirty=!1,this.m=b&&b.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new n(this.m)}copyInto(b){b.m[0]=this.m[0],b.m[1]=this.m[1],b.m[2]=this.m[2],b.m[3]=this.m[3],b.m[4]=this.m[4],b.m[5]=this.m[5]}point(b){var _=this.m;return{x:_[0]*b.x+_[2]*b.y+_[4],y:_[1]*b.x+_[3]*b.y+_[5]}}translate(b,_){return this.m[4]+=this.m[0]*b+this.m[2]*_,this.m[5]+=this.m[1]*b+this.m[3]*_,this}scale(b,_){return this.m[0]*=b,this.m[1]*=b,this.m[2]*=_,this.m[3]*=_,this}rotate(b){var _=Math.cos(b),w=Math.sin(b),x=this.m[0]*_+this.m[2]*w,T=this.m[1]*_+this.m[3]*w,P=this.m[0]*-w+this.m[2]*_,E=this.m[1]*-w+this.m[3]*_;return this.m[0]=x,this.m[1]=T,this.m[2]=P,this.m[3]=E,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(b,_){var w=this.m[0]+this.m[2]*_,x=this.m[1]+this.m[3]*_,T=this.m[2]+this.m[0]*b,P=this.m[3]+this.m[1]*b;return this.m[0]=w,this.m[1]=x,this.m[2]=T,this.m[3]=P,this}multiply(b){var _=this.m[0]*b.m[0]+this.m[2]*b.m[1],w=this.m[1]*b.m[0]+this.m[3]*b.m[1],x=this.m[0]*b.m[2]+this.m[2]*b.m[3],T=this.m[1]*b.m[2]+this.m[3]*b.m[3],P=this.m[0]*b.m[4]+this.m[2]*b.m[5]+this.m[4],E=this.m[1]*b.m[4]+this.m[3]*b.m[5]+this.m[5];return this.m[0]=_,this.m[1]=w,this.m[2]=x,this.m[3]=T,this.m[4]=P,this.m[5]=E,this}invert(){var b=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),_=this.m[3]*b,w=-this.m[1]*b,x=-this.m[2]*b,T=this.m[0]*b,P=b*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),E=b*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=_,this.m[1]=w,this.m[2]=x,this.m[3]=T,this.m[4]=P,this.m[5]=E,this}getMatrix(){return this.m}decompose(){var b=this.m[0],_=this.m[1],w=this.m[2],x=this.m[3],T=this.m[4],P=this.m[5],E=b*x-_*w;let A={x:T,y:P,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(b!=0||_!=0){var $=Math.sqrt(b*b+_*_);A.rotation=_>0?Math.acos(b/$):-Math.acos(b/$),A.scaleX=$,A.scaleY=E/$,A.skewX=(b*w+_*x)/E,A.skewY=0}else if(w!=0||x!=0){var M=Math.sqrt(w*w+x*x);A.rotation=Math.PI/2-(x>0?Math.acos(-w/M):-Math.acos(w/M)),A.scaleX=E/M,A.scaleY=M,A.skewX=0,A.skewY=(b*w+_*x)/E}return A.rotation=e.Util._getRotation(A.rotation),A}}e.Transform=n;var r="[object Array]",i="[object Number]",o="[object String]",s="[object Boolean]",a=Math.PI/180,l=180/Math.PI,u="#",c="",d="0",f="Konva warning: ",h="Konva error: ",p="rgb(",m={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},S=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/,v=[];const y=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(g){setTimeout(g,60)};e.Util={_isElement(g){return!!(g&&g.nodeType==1)},_isFunction(g){return!!(g&&g.constructor&&g.call&&g.apply)},_isPlainObject(g){return!!g&&g.constructor===Object},_isArray(g){return Object.prototype.toString.call(g)===r},_isNumber(g){return Object.prototype.toString.call(g)===i&&!isNaN(g)&&isFinite(g)},_isString(g){return Object.prototype.toString.call(g)===o},_isBoolean(g){return Object.prototype.toString.call(g)===s},isObject(g){return g instanceof Object},isValidSelector(g){if(typeof g!="string")return!1;var b=g[0];return b==="#"||b==="."||b===b.toUpperCase()},_sign(g){return g===0||g>0?1:-1},requestAnimFrame(g){v.push(g),v.length===1&&y(function(){const b=v;v=[],b.forEach(function(_){_()})})},createCanvasElement(){var g=document.createElement("canvas");try{g.style=g.style||{}}catch{}return g},createImageElement(){return document.createElement("img")},_isInDocument(g){for(;g=g.parentNode;)if(g==document)return!0;return!1},_urlToImage(g,b){var _=e.Util.createImageElement();_.onload=function(){b(_)},_.src=g},_rgbToHex(g,b,_){return((1<<24)+(g<<16)+(b<<8)+_).toString(16).slice(1)},_hexToRgb(g){g=g.replace(u,c);var b=parseInt(g,16);return{r:b>>16&255,g:b>>8&255,b:b&255}},getRandomColor(){for(var g=(Math.random()*16777215<<0).toString(16);g.length<6;)g=d+g;return u+g},getRGB(g){var b;return g in m?(b=m[g],{r:b[0],g:b[1],b:b[2]}):g[0]===u?this._hexToRgb(g.substring(1)):g.substr(0,4)===p?(b=S.exec(g.replace(/ /g,"")),{r:parseInt(b[1],10),g:parseInt(b[2],10),b:parseInt(b[3],10)}):{r:0,g:0,b:0}},colorToRGBA(g){return g=g||"black",e.Util._namedColorToRBA(g)||e.Util._hex3ColorToRGBA(g)||e.Util._hex4ColorToRGBA(g)||e.Util._hex6ColorToRGBA(g)||e.Util._hex8ColorToRGBA(g)||e.Util._rgbColorToRGBA(g)||e.Util._rgbaColorToRGBA(g)||e.Util._hslColorToRGBA(g)},_namedColorToRBA(g){var b=m[g.toLowerCase()];return b?{r:b[0],g:b[1],b:b[2],a:1}:null},_rgbColorToRGBA(g){if(g.indexOf("rgb(")===0){g=g.match(/rgb\(([^)]+)\)/)[1];var b=g.split(/ *, */).map(Number);return{r:b[0],g:b[1],b:b[2],a:1}}},_rgbaColorToRGBA(g){if(g.indexOf("rgba(")===0){g=g.match(/rgba\(([^)]+)\)/)[1];var b=g.split(/ *, */).map((_,w)=>_.slice(-1)==="%"?w===3?parseInt(_)/100:parseInt(_)/100*255:Number(_));return{r:b[0],g:b[1],b:b[2],a:b[3]}}},_hex8ColorToRGBA(g){if(g[0]==="#"&&g.length===9)return{r:parseInt(g.slice(1,3),16),g:parseInt(g.slice(3,5),16),b:parseInt(g.slice(5,7),16),a:parseInt(g.slice(7,9),16)/255}},_hex6ColorToRGBA(g){if(g[0]==="#"&&g.length===7)return{r:parseInt(g.slice(1,3),16),g:parseInt(g.slice(3,5),16),b:parseInt(g.slice(5,7),16),a:1}},_hex4ColorToRGBA(g){if(g[0]==="#"&&g.length===5)return{r:parseInt(g[1]+g[1],16),g:parseInt(g[2]+g[2],16),b:parseInt(g[3]+g[3],16),a:parseInt(g[4]+g[4],16)/255}},_hex3ColorToRGBA(g){if(g[0]==="#"&&g.length===4)return{r:parseInt(g[1]+g[1],16),g:parseInt(g[2]+g[2],16),b:parseInt(g[3]+g[3],16),a:1}},_hslColorToRGBA(g){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(g)){const[b,..._]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(g),w=Number(_[0])/360,x=Number(_[1])/100,T=Number(_[2])/100;let P,E,A;if(x===0)return A=T*255,{r:Math.round(A),g:Math.round(A),b:Math.round(A),a:1};T<.5?P=T*(1+x):P=T+x-T*x;const $=2*T-P,M=[0,0,0];for(let C=0;C<3;C++)E=w+1/3*-(C-1),E<0&&E++,E>1&&E--,6*E<1?A=$+(P-$)*6*E:2*E<1?A=P:3*E<2?A=$+(P-$)*(2/3-E)*6:A=$,M[C]=A*255;return{r:Math.round(M[0]),g:Math.round(M[1]),b:Math.round(M[2]),a:1}}},haveIntersection(g,b){return!(b.x>g.x+g.width||b.x+b.widthg.y+g.height||b.y+b.height1?(P=_,E=w,A=(_-x)*(_-x)+(w-T)*(w-T)):(P=g+M*(_-g),E=b+M*(w-b),A=(P-x)*(P-x)+(E-T)*(E-T))}return[P,E,A]},_getProjectionToLine(g,b,_){var w=e.Util.cloneObject(g),x=Number.MAX_VALUE;return b.forEach(function(T,P){if(!(!_&&P===b.length-1)){var E=b[(P+1)%b.length],A=e.Util._getProjectionToSegment(T.x,T.y,E.x,E.y,g.x,g.y),$=A[0],M=A[1],C=A[2];Cb.length){var P=b;b=g,g=P}for(w=0;w{b.width=0,b.height=0})},drawRoundedRectPath(g,b,_,w){let x=0,T=0,P=0,E=0;typeof w=="number"?x=T=P=E=Math.min(w,b/2,_/2):(x=Math.min(w[0]||0,b/2,_/2),T=Math.min(w[1]||0,b/2,_/2),E=Math.min(w[2]||0,b/2,_/2),P=Math.min(w[3]||0,b/2,_/2)),g.moveTo(x,0),g.lineTo(b-T,0),g.arc(b-T,T,T,Math.PI*3/2,0,!1),g.lineTo(b,_-E),g.arc(b-E,_-E,E,0,Math.PI/2,!1),g.lineTo(P,_),g.arc(P,_-P,P,Math.PI/2,Math.PI,!1),g.lineTo(0,x),g.arc(x,x,x,Math.PI,Math.PI*3/2,!1)}}})(Rt);var wt={},Te={},de={};Object.defineProperty(de,"__esModule",{value:!0});de.getComponentValidator=de.getBooleanValidator=de.getNumberArrayValidator=de.getFunctionValidator=de.getStringOrGradientValidator=de.getStringValidator=de.getNumberOrAutoValidator=de.getNumberOrArrayOfNumbersValidator=de.getNumberValidator=de.alphaComponent=de.RGBComponent=void 0;const Ko=Pe,Nt=Rt;function Xo(e){return Nt.Util._isString(e)?'"'+e+'"':Object.prototype.toString.call(e)==="[object Number]"||Nt.Util._isBoolean(e)?e:Object.prototype.toString.call(e)}function mce(e){return e>255?255:e<0?0:Math.round(e)}de.RGBComponent=mce;function yce(e){return e>1?1:e<1e-4?1e-4:e}de.alphaComponent=yce;function vce(){if(Ko.Konva.isUnminified)return function(e,t){return Nt.Util._isNumber(e)||Nt.Util.warn(Xo(e)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),e}}de.getNumberValidator=vce;function bce(e){if(Ko.Konva.isUnminified)return function(t,n){let r=Nt.Util._isNumber(t),i=Nt.Util._isArray(t)&&t.length==e;return!r&&!i&&Nt.Util.warn(Xo(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array('+e+")"),t}}de.getNumberOrArrayOfNumbersValidator=bce;function Sce(){if(Ko.Konva.isUnminified)return function(e,t){var n=Nt.Util._isNumber(e),r=e==="auto";return n||r||Nt.Util.warn(Xo(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),e}}de.getNumberOrAutoValidator=Sce;function _ce(){if(Ko.Konva.isUnminified)return function(e,t){return Nt.Util._isString(e)||Nt.Util.warn(Xo(e)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),e}}de.getStringValidator=_ce;function wce(){if(Ko.Konva.isUnminified)return function(e,t){const n=Nt.Util._isString(e),r=Object.prototype.toString.call(e)==="[object CanvasGradient]"||e&&e.addColorStop;return n||r||Nt.Util.warn(Xo(e)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),e}}de.getStringOrGradientValidator=wce;function xce(){if(Ko.Konva.isUnminified)return function(e,t){return Nt.Util._isFunction(e)||Nt.Util.warn(Xo(e)+' is a not valid value for "'+t+'" attribute. The value should be a function.'),e}}de.getFunctionValidator=xce;function Cce(){if(Ko.Konva.isUnminified)return function(e,t){const n=Int8Array?Object.getPrototypeOf(Int8Array):null;return n&&e instanceof n||(Nt.Util._isArray(e)?e.forEach(function(r){Nt.Util._isNumber(r)||Nt.Util.warn('"'+t+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):Nt.Util.warn(Xo(e)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),e}}de.getNumberArrayValidator=Cce;function Tce(){if(Ko.Konva.isUnminified)return function(e,t){var n=e===!0||e===!1;return n||Nt.Util.warn(Xo(e)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),e}}de.getBooleanValidator=Tce;function Ece(e){if(Ko.Konva.isUnminified)return function(t,n){return t==null||Nt.Util.isObject(t)||Nt.Util.warn(Xo(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+e),t}}de.getComponentValidator=Ece;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Factory=void 0;const t=Rt,n=de;var r="get",i="set";e.Factory={addGetterSetter(o,s,a,l,u){e.Factory.addGetter(o,s,a),e.Factory.addSetter(o,s,l,u),e.Factory.addOverloadedGetterSetter(o,s)},addGetter(o,s,a){var l=r+t.Util._capitalize(s);o.prototype[l]=o.prototype[l]||function(){var u=this.attrs[s];return u===void 0?a:u}},addSetter(o,s,a,l){var u=i+t.Util._capitalize(s);o.prototype[u]||e.Factory.overWriteSetter(o,s,a,l)},overWriteSetter(o,s,a,l){var u=i+t.Util._capitalize(s);o.prototype[u]=function(c){return a&&c!==void 0&&c!==null&&(c=a.call(this,c,s)),this._setAttr(s,c),l&&l.call(this),this}},addComponentsGetterSetter(o,s,a,l,u){var c=a.length,d=t.Util._capitalize,f=r+d(s),h=i+d(s),p,m;o.prototype[f]=function(){var v={};for(p=0;p{this._setAttr(s+d(b),void 0)}),this._fireChangeEvent(s,y,v),u&&u.call(this),this},e.Factory.addOverloadedGetterSetter(o,s)},addOverloadedGetterSetter(o,s){var a=t.Util._capitalize(s),l=i+a,u=r+a;o.prototype[s]=function(){return arguments.length?(this[l](arguments[0]),this):this[u]()}},addDeprecatedGetterSetter(o,s,a,l){t.Util.error("Adding deprecated "+s);var u=r+t.Util._capitalize(s),c=s+" property is deprecated and will be removed soon. Look at Konva change log for more information.";o.prototype[u]=function(){t.Util.error(c);var d=this.attrs[s];return d===void 0?a:d},e.Factory.addSetter(o,s,l,function(){t.Util.error(c)}),e.Factory.addOverloadedGetterSetter(o,s)},backCompat(o,s){t.Util.each(s,function(a,l){var u=o.prototype[l],c=r+t.Util._capitalize(a),d=i+t.Util._capitalize(a);function f(){u.apply(this,arguments),t.Util.error('"'+a+'" method is deprecated and will be removed soon. Use ""'+l+'" instead.')}o.prototype[a]=f,o.prototype[c]=f,o.prototype[d]=f})},afterSetFilter(){this._filterUpToDate=!1}}})(Te);var _i={},Ro={};Object.defineProperty(Ro,"__esModule",{value:!0});Ro.HitContext=Ro.SceneContext=Ro.Context=void 0;const sN=Rt,Pce=Pe;function Ace(e){var t=[],n=e.length,r=sN.Util,i,o;for(i=0;itypeof c=="number"?Math.floor(c):c)),o+=kce+u.join(YE)+Oce)):(o+=a.property,t||(o+=Dce+a.val)),o+=Mce;return o}clearTrace(){this.traceArr=[]}_trace(t){var n=this.traceArr,r;n.push(t),r=n.length,r>=$ce&&n.shift()}reset(){var t=this.getCanvas().getPixelRatio();this.setTransform(1*t,0,0,1*t,0,0)}getCanvas(){return this.canvas}clear(t){var n=this.getCanvas();t?this.clearRect(t.x||0,t.y||0,t.width||0,t.height||0):this.clearRect(0,0,n.getWidth()/n.pixelRatio,n.getHeight()/n.pixelRatio)}_applyLineCap(t){const n=t.attrs.lineCap;n&&this.setAttr("lineCap",n)}_applyOpacity(t){var n=t.getAbsoluteOpacity();n!==1&&this.setAttr("globalAlpha",n)}_applyLineJoin(t){const n=t.attrs.lineJoin;n&&this.setAttr("lineJoin",n)}setAttr(t,n){this._context[t]=n}arc(t,n,r,i,o,s){this._context.arc(t,n,r,i,o,s)}arcTo(t,n,r,i,o){this._context.arcTo(t,n,r,i,o)}beginPath(){this._context.beginPath()}bezierCurveTo(t,n,r,i,o,s){this._context.bezierCurveTo(t,n,r,i,o,s)}clearRect(t,n,r,i){this._context.clearRect(t,n,r,i)}clip(...t){this._context.clip.apply(this._context,t)}closePath(){this._context.closePath()}createImageData(t,n){var r=arguments;if(r.length===2)return this._context.createImageData(t,n);if(r.length===1)return this._context.createImageData(t)}createLinearGradient(t,n,r,i){return this._context.createLinearGradient(t,n,r,i)}createPattern(t,n){return this._context.createPattern(t,n)}createRadialGradient(t,n,r,i,o,s){return this._context.createRadialGradient(t,n,r,i,o,s)}drawImage(t,n,r,i,o,s,a,l,u){var c=arguments,d=this._context;c.length===3?d.drawImage(t,n,r):c.length===5?d.drawImage(t,n,r,i,o):c.length===9&&d.drawImage(t,n,r,i,o,s,a,l,u)}ellipse(t,n,r,i,o,s,a,l){this._context.ellipse(t,n,r,i,o,s,a,l)}isPointInPath(t,n,r,i){return r?this._context.isPointInPath(r,t,n,i):this._context.isPointInPath(t,n,i)}fill(...t){this._context.fill.apply(this._context,t)}fillRect(t,n,r,i){this._context.fillRect(t,n,r,i)}strokeRect(t,n,r,i){this._context.strokeRect(t,n,r,i)}fillText(t,n,r,i){i?this._context.fillText(t,n,r,i):this._context.fillText(t,n,r)}measureText(t){return this._context.measureText(t)}getImageData(t,n,r,i){return this._context.getImageData(t,n,r,i)}lineTo(t,n){this._context.lineTo(t,n)}moveTo(t,n){this._context.moveTo(t,n)}rect(t,n,r,i){this._context.rect(t,n,r,i)}putImageData(t,n,r){this._context.putImageData(t,n,r)}quadraticCurveTo(t,n,r,i){this._context.quadraticCurveTo(t,n,r,i)}restore(){this._context.restore()}rotate(t){this._context.rotate(t)}save(){this._context.save()}scale(t,n){this._context.scale(t,n)}setLineDash(t){this._context.setLineDash?this._context.setLineDash(t):"mozDash"in this._context?this._context.mozDash=t:"webkitLineDash"in this._context&&(this._context.webkitLineDash=t)}getLineDash(){return this._context.getLineDash()}setTransform(t,n,r,i,o,s){this._context.setTransform(t,n,r,i,o,s)}stroke(t){t?this._context.stroke(t):this._context.stroke()}strokeText(t,n,r,i){this._context.strokeText(t,n,r,i)}transform(t,n,r,i,o,s){this._context.transform(t,n,r,i,o,s)}translate(t,n){this._context.translate(t,n)}_enableTrace(){var t=this,n=QE.length,r=this.setAttr,i,o,s=function(a){var l=t[a],u;t[a]=function(){return o=Ace(Array.prototype.slice.call(arguments,0)),u=l.apply(t,arguments),t._trace({method:a,args:o}),u}};for(i=0;i{i.dragStatus==="dragging"&&(r=!0)}),r},justDragged:!1,get node(){var r;return e.DD._dragElements.forEach(i=>{r=i.node}),r},_dragElements:new Map,_drag(r){const i=[];e.DD._dragElements.forEach((o,s)=>{const{node:a}=o,l=a.getStage();l.setPointersPositions(r),o.pointerId===void 0&&(o.pointerId=n.Util._getFirstPointerId(r));const u=l._changedPointerPositions.find(f=>f.id===o.pointerId);if(u){if(o.dragStatus!=="dragging"){var c=a.dragDistance(),d=Math.max(Math.abs(u.x-o.startPointerPos.x),Math.abs(u.y-o.startPointerPos.y));if(d{o.fire("dragmove",{type:"dragmove",target:o,evt:r},!0)})},_endDragBefore(r){const i=[];e.DD._dragElements.forEach(o=>{const{node:s}=o,a=s.getStage();if(r&&a.setPointersPositions(r),!a._changedPointerPositions.find(c=>c.id===o.pointerId))return;(o.dragStatus==="dragging"||o.dragStatus==="stopped")&&(e.DD.justDragged=!0,t.Konva._mouseListenClick=!1,t.Konva._touchListenClick=!1,t.Konva._pointerListenClick=!1,o.dragStatus="stopped");const u=o.node.getLayer()||o.node instanceof t.Konva.Stage&&o.node;u&&i.indexOf(u)===-1&&i.push(u)}),i.forEach(o=>{o.draw()})},_endDragAfter(r){e.DD._dragElements.forEach((i,o)=>{i.dragStatus==="stopped"&&i.node.fire("dragend",{type:"dragend",target:i.node,evt:r},!0),i.dragStatus!=="dragging"&&e.DD._dragElements.delete(o)})}},t.Konva.isBrowser&&(window.addEventListener("mouseup",e.DD._endDragBefore,!0),window.addEventListener("touchend",e.DD._endDragBefore,!0),window.addEventListener("mousemove",e.DD._drag),window.addEventListener("touchmove",e.DD._drag),window.addEventListener("mouseup",e.DD._endDragAfter,!1),window.addEventListener("touchend",e.DD._endDragAfter,!1))})(ov);Object.defineProperty(wt,"__esModule",{value:!0});wt.Node=void 0;const ke=Rt,Ah=Te,Dp=_i,ya=Pe,Br=ov,zt=de;var bg="absoluteOpacity",Lp="allEventListeners",bo="absoluteTransform",ZE="absoluteScale",va="canvas",Hce="Change",qce="children",Wce="konva",g2="listening",JE="mouseenter",e6="mouseleave",t6="set",n6="Shape",Sg=" ",r6="stage",ss="transform",Kce="Stage",m2="visible",Xce=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Sg);let Yce=1,Se=class y2{constructor(t){this._id=Yce++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(t),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(t){(t===ss||t===bo)&&this._cache.get(t)?this._cache.get(t).dirty=!0:t?this._cache.delete(t):this._cache.clear()}_getCache(t,n){var r=this._cache.get(t),i=t===ss||t===bo,o=r===void 0||i&&r.dirty===!0;return o&&(r=n.call(this),this._cache.set(t,r)),r}_calculate(t,n,r){if(!this._attachedDepsListeners.get(t)){const i=n.map(o=>o+"Change.konva").join(Sg);this.on(i,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,r)}_getCanvasCache(){return this._cache.get(va)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===bo&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(va)){const{scene:t,filter:n,hit:r}=this._cache.get(va);ke.Util.releaseCanvas(t,n,r),this._cache.delete(va)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(t){var n=t||{},r={};(n.x===void 0||n.y===void 0||n.width===void 0||n.height===void 0)&&(r=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()}));var i=Math.ceil(n.width||r.width),o=Math.ceil(n.height||r.height),s=n.pixelRatio,a=n.x===void 0?Math.floor(r.x):n.x,l=n.y===void 0?Math.floor(r.y):n.y,u=n.offset||0,c=n.drawBorder||!1,d=n.hitCanvasPixelRatio||1;if(!i||!o){ke.Util.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}i+=u*2+1,o+=u*2+1,a-=u,l-=u;var f=new Dp.SceneCanvas({pixelRatio:s,width:i,height:o}),h=new Dp.SceneCanvas({pixelRatio:s,width:0,height:0,willReadFrequently:!0}),p=new Dp.HitCanvas({pixelRatio:d,width:i,height:o}),m=f.getContext(),S=p.getContext();return p.isCache=!0,f.isCache=!0,this._cache.delete(va),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(f.getContext()._context.imageSmoothingEnabled=!1,h.getContext()._context.imageSmoothingEnabled=!1),m.save(),S.save(),m.translate(-a,-l),S.translate(-a,-l),this._isUnderCache=!0,this._clearSelfAndDescendantCache(bg),this._clearSelfAndDescendantCache(ZE),this.drawScene(f,this),this.drawHit(p,this),this._isUnderCache=!1,m.restore(),S.restore(),c&&(m.save(),m.beginPath(),m.rect(0,0,i,o),m.closePath(),m.setAttr("strokeStyle","red"),m.setAttr("lineWidth",5),m.stroke(),m.restore()),this._cache.set(va,{scene:f,filter:h,hit:p,x:a,y:l}),this._requestDraw(),this}isCached(){return this._cache.has(va)}getClientRect(t){throw new Error('abstract "getClientRect" method call')}_transformedRect(t,n){var r=[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x+t.width,y:t.y+t.height},{x:t.x,y:t.y+t.height}],i,o,s,a,l=this.getAbsoluteTransform(n);return r.forEach(function(u){var c=l.point(u);i===void 0&&(i=s=c.x,o=a=c.y),i=Math.min(i,c.x),o=Math.min(o,c.y),s=Math.max(s,c.x),a=Math.max(a,c.y)}),{x:i,y:o,width:s-i,height:a-o}}_drawCachedSceneCanvas(t){t.save(),t._applyOpacity(this),t._applyGlobalCompositeOperation(this);const n=this._getCanvasCache();t.translate(n.x,n.y);var r=this._getCachedSceneCanvas(),i=r.pixelRatio;t.drawImage(r._canvas,0,0,r.width/i,r.height/i),t.restore()}_drawCachedHitCanvas(t){var n=this._getCanvasCache(),r=n.hit;t.save(),t.translate(n.x,n.y),t.drawImage(r._canvas,0,0,r.width/r.pixelRatio,r.height/r.pixelRatio),t.restore()}_getCachedSceneCanvas(){var t=this.filters(),n=this._getCanvasCache(),r=n.scene,i=n.filter,o=i.getContext(),s,a,l,u;if(t){if(!this._filterUpToDate){var c=r.pixelRatio;i.setSize(r.width/r.pixelRatio,r.height/r.pixelRatio);try{for(s=t.length,o.clear(),o.drawImage(r._canvas,0,0,r.getWidth()/c,r.getHeight()/c),a=o.getImageData(0,0,i.getWidth(),i.getHeight()),l=0;l{var n,r;if(!t)return this;for(n in t)n!==qce&&(r=t6+ke.Util._capitalize(n),ke.Util._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(g2,this._isListening)}_isListening(t){if(!this.listening())return!1;const r=this.getParent();return r&&r!==t&&this!==t?r._isListening(t):!0}isVisible(){return this._getCache(m2,this._isVisible)}_isVisible(t){if(!this.visible())return!1;const r=this.getParent();return r&&r!==t&&this!==t?r._isVisible(t):!0}shouldDrawHit(t,n=!1){if(t)return this._isVisible(t)&&this._isListening(t);var r=this.getLayer(),i=!1;Br.DD._dragElements.forEach(s=>{s.dragStatus==="dragging"&&(s.node.nodeType==="Stage"||s.node.getLayer()===r)&&(i=!0)});var o=!n&&!ya.Konva.hitOnDragEnabled&&i;return this.isListening()&&this.isVisible()&&!o}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){var t=this.getDepth(),n=this,r=0,i,o,s,a;function l(u){for(i=[],o=u.length,s=0;s0&&i[0].getDepth()<=t&&l(i)}return n.nodeType!==Kce&&l(n.getStage().getChildren()),r}getDepth(){for(var t=0,n=this.parent;n;)t++,n=n.parent;return t}_batchTransformChanges(t){this._batchingTransformChange=!0,t(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache(ss),this._clearSelfAndDescendantCache(bo)),this._needClearTransformCache=!1}setPosition(t){return this._batchTransformChanges(()=>{this.x(t.x),this.y(t.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){if(!this.getStage())return null;var t=this.getStage().getPointerPosition();if(!t)return null;var n=this.getAbsoluteTransform().copy();return n.invert(),n.point(t)}getAbsolutePosition(t){let n=!1,r=this.parent;for(;r;){if(r.isCached()){n=!0;break}r=r.parent}n&&!t&&(t=!0);var i=this.getAbsoluteTransform(t).getMatrix(),o=new ke.Transform,s=this.offset();return o.m=i.slice(),o.translate(s.x,s.y),o.getTranslation()}setAbsolutePosition(t){var n=this._clearTransform();this.attrs.x=n.x,this.attrs.y=n.y,delete n.x,delete n.y,this._clearCache(ss);var r=this._getAbsoluteTransform().copy();return r.invert(),r.translate(t.x,t.y),t={x:this.attrs.x+r.getTranslation().x,y:this.attrs.y+r.getTranslation().y},this._setTransform(n),this.setPosition({x:t.x,y:t.y}),this._clearCache(ss),this._clearSelfAndDescendantCache(bo),this}_setTransform(t){var n;for(n in t)this.attrs[n]=t[n]}_clearTransform(){var t={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,t}move(t){var n=t.x,r=t.y,i=this.x(),o=this.y();return n!==void 0&&(i+=n),r!==void 0&&(o+=r),this.setPosition({x:i,y:o}),this}_eachAncestorReverse(t,n){var r=[],i=this.getParent(),o,s;if(!(n&&n._id===this._id)){for(r.unshift(this);i&&(!n||i._id!==n._id);)r.unshift(i),i=i.parent;for(o=r.length,s=0;s0?(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return ke.Util.warn("Node has no parent. moveToBottom function is ignored."),!1;var t=this.index;return t>0?(this.parent.children.splice(t,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1}setZIndex(t){if(!this.parent)return ke.Util.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&ke.Util.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");var n=this.index;return this.parent.children.splice(n,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(bg,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){var t=this.opacity(),n=this.getParent();return n&&!n._isUnderCache&&(t*=n.getAbsoluteOpacity()),t}moveTo(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this}toObject(){var t={},n=this.getAttrs(),r,i,o,s,a;t.attrs={};for(r in n)i=n[r],a=ke.Util.isObject(i)&&!ke.Util._isPlainObject(i)&&!ke.Util._isArray(i),!a&&(o=typeof this[r]=="function"&&this[r],delete n[r],s=o?o.call(this):null,n[r]=i,s!==i&&(t.attrs[r]=i));return t.className=this.getClassName(),ke.Util._prepareToStringify(t)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(t,n,r){var i=[];n&&this._isMatch(t)&&i.push(this);for(var o=this.parent;o;){if(o===r)return i;o._isMatch(t)&&i.push(o),o=o.parent}return i}isAncestorOf(t){return!1}findAncestor(t,n,r){return this.findAncestors(t,n,r)[0]}_isMatch(t){if(!t)return!1;if(typeof t=="function")return t(this);var n=t.replace(/ /g,"").split(","),r=n.length,i,o;for(i=0;i{try{const i=t==null?void 0:t.callback;i&&delete t.callback,ke.Util._urlToImage(this.toDataURL(t),function(o){n(o),i==null||i(o)})}catch(i){r(i)}})}toBlob(t){return new Promise((n,r)=>{try{const i=t==null?void 0:t.callback;i&&delete t.callback,this.toCanvas(t).toBlob(o=>{n(o),i==null||i(o)})}catch(i){r(i)}})}setSize(t){return this.width(t.width),this.height(t.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){return this.attrs.dragDistance!==void 0?this.attrs.dragDistance:this.parent?this.parent.getDragDistance():ya.Konva.dragDistance}_off(t,n,r){var i=this.eventListeners[t],o,s,a;for(o=0;o=0;if(r&&!this.isDragging()){var i=!1;Br.DD._dragElements.forEach(o=>{this.isAncestorOf(o.node)&&(i=!0)}),i||this._createDragElement(t)}})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{this._dragCleanup();var t=this.getStage();if(!t)return;const n=Br.DD._dragElements.get(this._id),r=n&&n.dragStatus==="dragging",i=n&&n.dragStatus==="ready";r?this.stopDrag():i&&Br.DD._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(t={x:0,y:0}){const n=this.getStage();if(!n)return!1;const r={x:-t.x,y:-t.y,width:n.width()+2*t.x,height:n.height()+2*t.y};return ke.Util.haveIntersection(r,this.getClientRect())}static create(t,n){return ke.Util._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){var r=y2.prototype.getClassName.call(t),i=t.children,o,s,a;n&&(t.attrs.container=n),ya.Konva[r]||(ke.Util.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const l=ya.Konva[r];if(o=new l(t.attrs),i)for(s=i.length,a=0;a0}removeChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.destroy()}),this.children=[],this._requestDraw(),this}add(...t){if(t.length===0)return this;if(t.length>1){for(var n=0;n0?n[0]:void 0}_generalFind(t,n){var r=[];return this._descendants(i=>{const o=i._isMatch(t);return o&&r.push(i),!!(o&&n)}),r}_descendants(t){let n=!1;const r=this.getChildren();for(const i of r){if(n=t(i),n)return!0;if(i.hasChildren()&&(n=i._descendants(t),n))return!0}return!1}toObject(){var t=Ub.Node.prototype.toObject.call(this);return t.children=[],this.getChildren().forEach(n=>{t.children.push(n.toObject())}),t}isAncestorOf(t){for(var n=t.getParent();n;){if(n._id===this._id)return!0;n=n.getParent()}return!1}clone(t){var n=Ub.Node.prototype.clone.call(this,t);return this.getChildren().forEach(function(r){n.add(r.clone())}),n}getAllIntersections(t){var n=[];return this.find("Shape").forEach(function(r){r.isVisible()&&r.intersects(t)&&n.push(r)}),n}_clearSelfAndDescendantCache(t){var n;super._clearSelfAndDescendantCache(t),!this.isCached()&&((n=this.children)===null||n===void 0||n.forEach(function(r){r._clearSelfAndDescendantCache(t)}))}_setChildrenIndices(){var t;(t=this.children)===null||t===void 0||t.forEach(function(n,r){n.index=r}),this._requestDraw()}drawScene(t,n){var r=this.getLayer(),i=t||r&&r.getCanvas(),o=i&&i.getContext(),s=this._getCanvasCache(),a=s&&s.scene,l=i&&i.isCache;if(!this.isVisible()&&!l)return this;if(a){o.save();var u=this.getAbsoluteTransform(n).getMatrix();o.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(o),o.restore()}else this._drawChildren("drawScene",i,n);return this}drawHit(t,n){if(!this.shouldDrawHit(n))return this;var r=this.getLayer(),i=t||r&&r.hitCanvas,o=i&&i.getContext(),s=this._getCanvasCache(),a=s&&s.hit;if(a){o.save();var l=this.getAbsoluteTransform(n).getMatrix();o.transform(l[0],l[1],l[2],l[3],l[4],l[5]),this._drawCachedHitCanvas(o),o.restore()}else this._drawChildren("drawHit",i,n);return this}_drawChildren(t,n,r){var i,o=n&&n.getContext(),s=this.clipWidth(),a=this.clipHeight(),l=this.clipFunc(),u=s&&a||l;const c=r===this;if(u){o.save();var d=this.getAbsoluteTransform(r),f=d.getMatrix();o.transform(f[0],f[1],f[2],f[3],f[4],f[5]),o.beginPath();let S;if(l)S=l.call(this,o,this);else{var h=this.clipX(),p=this.clipY();o.rect(h,p,s,a)}o.clip.apply(o,S),f=d.copy().invert().getMatrix(),o.transform(f[0],f[1],f[2],f[3],f[4],f[5])}var m=!c&&this.globalCompositeOperation()!=="source-over"&&t==="drawScene";m&&(o.save(),o._applyGlobalCompositeOperation(this)),(i=this.children)===null||i===void 0||i.forEach(function(S){S[t](n,r)}),m&&o.restore(),u&&o.restore()}getClientRect(t){var n;t=t||{};var r=t.skipTransform,i=t.relativeTo,o,s,a,l,u={x:1/0,y:1/0,width:0,height:0},c=this;(n=this.children)===null||n===void 0||n.forEach(function(m){if(m.visible()){var S=m.getClientRect({relativeTo:c,skipShadow:t.skipShadow,skipStroke:t.skipStroke});S.width===0&&S.height===0||(o===void 0?(o=S.x,s=S.y,a=S.x+S.width,l=S.y+S.height):(o=Math.min(o,S.x),s=Math.min(s,S.y),a=Math.max(a,S.x+S.width),l=Math.max(l,S.y+S.height)))}});for(var d=this.find("Shape"),f=!1,h=0;hY.indexOf("pointer")>=0?"pointer":Y.indexOf("touch")>=0?"touch":"mouse",U=Y=>{const B=j(Y);if(B==="pointer")return i.Konva.pointerEventsEnabled&&L.pointer;if(B==="touch")return L.touch;if(B==="mouse")return L.mouse};function G(Y={}){return(Y.clipFunc||Y.clipWidth||Y.clipHeight)&&t.Util.warn("Stage does not support clipping. Please use clip for Layers or Groups."),Y}const W="Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);";e.stages=[];class X extends r.Container{constructor(B){super(G(B)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),e.stages.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{G(this.attrs)}),this._checkVisibility()}_validateAdd(B){const H=B.getType()==="Layer",Q=B.getType()==="FastLayer";H||Q||t.Util.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const B=this.visible()?"":"none";this.content.style.display=B}setContainer(B){if(typeof B===c){if(B.charAt(0)==="."){var H=B.slice(1);B=document.getElementsByClassName(H)[0]}else{var Q;B.charAt(0)!=="#"?Q=B:Q=B.slice(1),B=document.getElementById(Q)}if(!B)throw"Can not find container in document with id "+Q}return this._setAttr("container",B),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),B.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){var B=this.children,H=B.length,Q;for(Q=0;Q-1&&e.stages.splice(H,1),t.Util.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const B=this._pointerPositions[0]||this._changedPointerPositions[0];return B?{x:B.x,y:B.y}:(t.Util.warn(W),null)}_getPointerById(B){return this._pointerPositions.find(H=>H.id===B)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(B){B=B||{},B.x=B.x||0,B.y=B.y||0,B.width=B.width||this.width(),B.height=B.height||this.height();var H=new o.SceneCanvas({width:B.width,height:B.height,pixelRatio:B.pixelRatio||1}),Q=H.getContext()._context,J=this.children;return(B.x||B.y)&&Q.translate(-1*B.x,-1*B.y),J.forEach(function(ne){if(ne.isVisible()){var te=ne._toKonvaCanvas(B);Q.drawImage(te._canvas,B.x,B.y,te.getWidth()/te.getPixelRatio(),te.getHeight()/te.getPixelRatio())}}),H}getIntersection(B){if(!B)return null;var H=this.children,Q=H.length,J=Q-1,ne;for(ne=J;ne>=0;ne--){const te=H[ne].getIntersection(B);if(te)return te}return null}_resizeDOM(){var B=this.width(),H=this.height();this.content&&(this.content.style.width=B+d,this.content.style.height=H+d),this.bufferCanvas.setSize(B,H),this.bufferHitCanvas.setSize(B,H),this.children.forEach(Q=>{Q.setSize({width:B,height:H}),Q.draw()})}add(B,...H){if(arguments.length>1){for(var Q=0;QR&&t.Util.warn("The stage has "+J+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),B.setSize({width:this.width(),height:this.height()}),B.draw(),i.Konva.isBrowser&&this.content.appendChild(B.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(B){return l.hasPointerCapture(B,this)}setPointerCapture(B){l.setPointerCapture(B,this)}releaseCapture(B){l.releaseCapture(B,this)}getLayers(){return this.children}_bindContentEvents(){i.Konva.isBrowser&&D.forEach(([B,H])=>{this.content.addEventListener(B,Q=>{this[H](Q)},{passive:!1})})}_pointerenter(B){this.setPointersPositions(B);const H=U(B.type);this._fire(H.pointerenter,{evt:B,target:this,currentTarget:this})}_pointerover(B){this.setPointersPositions(B);const H=U(B.type);this._fire(H.pointerover,{evt:B,target:this,currentTarget:this})}_getTargetShape(B){let H=this[B+"targetShape"];return H&&!H.getStage()&&(H=null),H}_pointerleave(B){const H=U(B.type),Q=j(B.type);if(H){this.setPointersPositions(B);var J=this._getTargetShape(Q),ne=!s.DD.isDragging||i.Konva.hitOnDragEnabled;J&&ne?(J._fireAndBubble(H.pointerout,{evt:B}),J._fireAndBubble(H.pointerleave,{evt:B}),this._fire(H.pointerleave,{evt:B,target:this,currentTarget:this}),this[Q+"targetShape"]=null):ne&&(this._fire(H.pointerleave,{evt:B,target:this,currentTarget:this}),this._fire(H.pointerout,{evt:B,target:this,currentTarget:this})),this.pointerPos=void 0,this._pointerPositions=[]}}_pointerdown(B){const H=U(B.type),Q=j(B.type);if(H){this.setPointersPositions(B);var J=!1;this._changedPointerPositions.forEach(ne=>{var te=this.getIntersection(ne);if(s.DD.justDragged=!1,i.Konva["_"+Q+"ListenClick"]=!0,!(te&&te.isListening()))return;i.Konva.capturePointerEventsEnabled&&te.setPointerCapture(ne.id),this[Q+"ClickStartShape"]=te,te._fireAndBubble(H.pointerdown,{evt:B,pointerId:ne.id}),J=!0;const ve=B.type.indexOf("touch")>=0;te.preventDefault()&&B.cancelable&&ve&&B.preventDefault()}),J||this._fire(H.pointerdown,{evt:B,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}}_pointermove(B){const H=U(B.type),Q=j(B.type);if(!H)return;s.DD.isDragging&&s.DD.node.preventDefault()&&B.cancelable&&B.preventDefault(),this.setPointersPositions(B);var J=!s.DD.isDragging||i.Konva.hitOnDragEnabled;if(!J)return;var ne={};let te=!1;var xe=this._getTargetShape(Q);this._changedPointerPositions.forEach(ve=>{const ce=l.getCapturedShape(ve.id)||this.getIntersection(ve),Ne=ve.id,se={evt:B,pointerId:Ne};var gt=xe!==ce;if(gt&&xe&&(xe._fireAndBubble(H.pointerout,Object.assign({},se),ce),xe._fireAndBubble(H.pointerleave,Object.assign({},se),ce)),ce){if(ne[ce._id])return;ne[ce._id]=!0}ce&&ce.isListening()?(te=!0,gt&&(ce._fireAndBubble(H.pointerover,Object.assign({},se),xe),ce._fireAndBubble(H.pointerenter,Object.assign({},se),xe),this[Q+"targetShape"]=ce),ce._fireAndBubble(H.pointermove,Object.assign({},se))):xe&&(this._fire(H.pointerover,{evt:B,target:this,currentTarget:this,pointerId:Ne}),this[Q+"targetShape"]=null)}),te||this._fire(H.pointermove,{evt:B,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(B){const H=U(B.type),Q=j(B.type);if(!H)return;this.setPointersPositions(B);const J=this[Q+"ClickStartShape"],ne=this[Q+"ClickEndShape"];var te={};let xe=!1;this._changedPointerPositions.forEach(ve=>{const ce=l.getCapturedShape(ve.id)||this.getIntersection(ve);if(ce){if(ce.releaseCapture(ve.id),te[ce._id])return;te[ce._id]=!0}const Ne=ve.id,se={evt:B,pointerId:Ne};let gt=!1;i.Konva["_"+Q+"InDblClickWindow"]?(gt=!0,clearTimeout(this[Q+"DblTimeout"])):s.DD.justDragged||(i.Konva["_"+Q+"InDblClickWindow"]=!0,clearTimeout(this[Q+"DblTimeout"])),this[Q+"DblTimeout"]=setTimeout(function(){i.Konva["_"+Q+"InDblClickWindow"]=!1},i.Konva.dblClickWindow),ce&&ce.isListening()?(xe=!0,this[Q+"ClickEndShape"]=ce,ce._fireAndBubble(H.pointerup,Object.assign({},se)),i.Konva["_"+Q+"ListenClick"]&&J&&J===ce&&(ce._fireAndBubble(H.pointerclick,Object.assign({},se)),gt&&ne&&ne===ce&&ce._fireAndBubble(H.pointerdblclick,Object.assign({},se)))):(this[Q+"ClickEndShape"]=null,i.Konva["_"+Q+"ListenClick"]&&this._fire(H.pointerclick,{evt:B,target:this,currentTarget:this,pointerId:Ne}),gt&&this._fire(H.pointerdblclick,{evt:B,target:this,currentTarget:this,pointerId:Ne}))}),xe||this._fire(H.pointerup,{evt:B,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),i.Konva["_"+Q+"ListenClick"]=!1,B.cancelable&&Q!=="touch"&&B.preventDefault()}_contextmenu(B){this.setPointersPositions(B);var H=this.getIntersection(this.getPointerPosition());H&&H.isListening()?H._fireAndBubble($,{evt:B}):this._fire($,{evt:B,target:this,currentTarget:this})}_wheel(B){this.setPointersPositions(B);var H=this.getIntersection(this.getPointerPosition());H&&H.isListening()?H._fireAndBubble(N,{evt:B}):this._fire(N,{evt:B,target:this,currentTarget:this})}_pointercancel(B){this.setPointersPositions(B);const H=l.getCapturedShape(B.pointerId)||this.getIntersection(this.getPointerPosition());H&&H._fireAndBubble(_,l.createEvent(B)),l.releaseCapture(B.pointerId)}_lostpointercapture(B){l.releaseCapture(B.pointerId)}setPointersPositions(B){var H=this._getContentPosition(),Q=null,J=null;B=B||window.event,B.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(B.touches,ne=>{this._pointerPositions.push({id:ne.identifier,x:(ne.clientX-H.left)/H.scaleX,y:(ne.clientY-H.top)/H.scaleY})}),Array.prototype.forEach.call(B.changedTouches||B.touches,ne=>{this._changedPointerPositions.push({id:ne.identifier,x:(ne.clientX-H.left)/H.scaleX,y:(ne.clientY-H.top)/H.scaleY})})):(Q=(B.clientX-H.left)/H.scaleX,J=(B.clientY-H.top)/H.scaleY,this.pointerPos={x:Q,y:J},this._pointerPositions=[{x:Q,y:J,id:t.Util._getFirstPointerId(B)}],this._changedPointerPositions=[{x:Q,y:J,id:t.Util._getFirstPointerId(B)}])}_setPointerPosition(B){t.Util.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(B)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};var B=this.content.getBoundingClientRect();return{top:B.top,left:B.left,scaleX:B.width/this.content.clientWidth||1,scaleY:B.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new o.SceneCanvas({width:this.width(),height:this.height()}),this.bufferHitCanvas=new o.HitCanvas({pixelRatio:1,width:this.width(),height:this.height()}),!!i.Konva.isBrowser){var B=this.container();if(!B)throw"Stage has no container. A container is required.";B.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),B.appendChild(this.content),this._resizeDOM()}}cache(){return t.Util.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(B){B.batchDraw()}),this}}e.Stage=X,X.prototype.nodeType=u,(0,a._registerNode)(X),n.Factory.addGetterSetter(X,"container")})(uN);var kh={},sn={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Shape=e.shapes=void 0;const t=Pe,n=Rt,r=Te,i=wt,o=de,s=Pe,a=Tr;var l="hasShadow",u="shadowRGBA",c="patternImage",d="linearGradient",f="radialGradient";let h;function p(){return h||(h=n.Util.createCanvasElement().getContext("2d"),h)}e.shapes={};function m(P){const E=this.attrs.fillRule;E?P.fill(E):P.fill()}function S(P){P.stroke()}function v(P){P.fill()}function y(P){P.stroke()}function g(){this._clearCache(l)}function b(){this._clearCache(u)}function _(){this._clearCache(c)}function w(){this._clearCache(d)}function x(){this._clearCache(f)}class T extends i.Node{constructor(E){super(E);let A;for(;A=n.Util.getRandomColor(),!(A&&!(A in e.shapes)););this.colorKey=A,e.shapes[A]=this}getContext(){return n.Util.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return n.Util.warn("shape.getCanvas() method is deprecated. Please do not use it."),this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache(l,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(c,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){var E=p();const A=E.createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(A&&A.setTransform){const $=new n.Transform;$.translate(this.fillPatternX(),this.fillPatternY()),$.rotate(t.Konva.getAngle(this.fillPatternRotation())),$.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),$.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const M=$.getMatrix(),C=typeof DOMMatrix>"u"?{a:M[0],b:M[1],c:M[2],d:M[3],e:M[4],f:M[5]}:new DOMMatrix(M);A.setTransform(C)}return A}}_getLinearGradient(){return this._getCache(d,this.__getLinearGradient)}__getLinearGradient(){var E=this.fillLinearGradientColorStops();if(E){for(var A=p(),$=this.fillLinearGradientStartPoint(),M=this.fillLinearGradientEndPoint(),C=A.createLinearGradient($.x,$.y,M.x,M.y),O=0;Othis.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!!(this.stroke()||this.strokeLinearGradientColorStops()))}hasHitStroke(){const E=this.hitStrokeWidth();return E==="auto"?this.hasStroke():this.strokeEnabled()&&!!E}intersects(E){var A=this.getStage(),$=A.bufferHitCanvas,M;return $.getContext().clear(),this.drawHit($,null,!0),M=$.context.getImageData(Math.round(E.x),Math.round(E.y),1,1).data,M[3]>0}destroy(){return i.Node.prototype.destroy.call(this),delete e.shapes[this.colorKey],delete this.colorKey,this}_useBufferCanvas(E){var A;if(!this.getStage()||!((A=this.attrs.perfectDrawEnabled)!==null&&A!==void 0?A:!0))return!1;const M=E||this.hasFill(),C=this.hasStroke(),O=this.getAbsoluteOpacity()!==1;if(M&&C&&O)return!0;const I=this.hasShadow(),N=this.shadowForStrokeEnabled();return!!(M&&C&&I&&N)}setStrokeHitEnabled(E){n.Util.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),E?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){var E=this.size();return{x:this._centroid?-E.width/2:0,y:this._centroid?-E.height/2:0,width:E.width,height:E.height}}getClientRect(E={}){const A=E.skipTransform,$=E.relativeTo,M=this.getSelfRect(),O=!E.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,I=M.width+O,N=M.height+O,R=!E.skipShadow&&this.hasShadow(),D=R?this.shadowOffsetX():0,L=R?this.shadowOffsetY():0,j=I+Math.abs(D),U=N+Math.abs(L),G=R&&this.shadowBlur()||0,W=j+G*2,X=U+G*2,Y={width:W,height:X,x:-(O/2+G)+Math.min(D,0)+M.x,y:-(O/2+G)+Math.min(L,0)+M.y};return A?Y:this._transformedRect(Y,$)}drawScene(E,A){var $=this.getLayer(),M=E||$.getCanvas(),C=M.getContext(),O=this._getCanvasCache(),I=this.getSceneFunc(),N=this.hasShadow(),R,D,L,j=M.isCache,U=A===this;if(!this.isVisible()&&!U)return this;if(O){C.save();var G=this.getAbsoluteTransform(A).getMatrix();return C.transform(G[0],G[1],G[2],G[3],G[4],G[5]),this._drawCachedSceneCanvas(C),C.restore(),this}if(!I)return this;if(C.save(),this._useBufferCanvas()&&!j){R=this.getStage(),D=R.bufferCanvas,L=D.getContext(),L.clear(),L.save(),L._applyLineJoin(this);var W=this.getAbsoluteTransform(A).getMatrix();L.transform(W[0],W[1],W[2],W[3],W[4],W[5]),I.call(this,L,this),L.restore();var X=D.pixelRatio;N&&C._applyShadow(this),C._applyOpacity(this),C._applyGlobalCompositeOperation(this),C.drawImage(D._canvas,0,0,D.width/X,D.height/X)}else{if(C._applyLineJoin(this),!U){var W=this.getAbsoluteTransform(A).getMatrix();C.transform(W[0],W[1],W[2],W[3],W[4],W[5]),C._applyOpacity(this),C._applyGlobalCompositeOperation(this)}N&&C._applyShadow(this),I.call(this,C,this)}return C.restore(),this}drawHit(E,A,$=!1){if(!this.shouldDrawHit(A,$))return this;var M=this.getLayer(),C=E||M.hitCanvas,O=C&&C.getContext(),I=this.hitFunc()||this.sceneFunc(),N=this._getCanvasCache(),R=N&&N.hit;if(this.colorKey||n.Util.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),R){O.save();var D=this.getAbsoluteTransform(A).getMatrix();return O.transform(D[0],D[1],D[2],D[3],D[4],D[5]),this._drawCachedHitCanvas(O),O.restore(),this}if(!I)return this;if(O.save(),O._applyLineJoin(this),!(this===A)){var j=this.getAbsoluteTransform(A).getMatrix();O.transform(j[0],j[1],j[2],j[3],j[4],j[5])}return I.call(this,O,this),O.restore(),this}drawHitFromCache(E=0){var A=this._getCanvasCache(),$=this._getCachedSceneCanvas(),M=A.hit,C=M.getContext(),O=M.getWidth(),I=M.getHeight(),N,R,D,L,j,U;C.clear(),C.drawImage($._canvas,0,0,O,I);try{for(N=C.getImageData(0,0,O,I),R=N.data,D=R.length,L=n.Util._hexToRgb(this.colorKey),j=0;jE?(R[j]=L.r,R[j+1]=L.g,R[j+2]=L.b,R[j+3]=255):R[j+3]=0;C.putImageData(N,0,0)}catch(G){n.Util.error("Unable to draw hit graph from cached scene canvas. "+G.message)}return this}hasPointerCapture(E){return a.hasPointerCapture(E,this)}setPointerCapture(E){a.setPointerCapture(E,this)}releaseCapture(E){a.releaseCapture(E,this)}}e.Shape=T,T.prototype._fillFunc=m,T.prototype._strokeFunc=S,T.prototype._fillFuncHit=v,T.prototype._strokeFuncHit=y,T.prototype._centroid=!1,T.prototype.nodeType="Shape",(0,s._registerNode)(T),T.prototype.eventListeners={},T.prototype.on.call(T.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",g),T.prototype.on.call(T.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",b),T.prototype.on.call(T.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",_),T.prototype.on.call(T.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",w),T.prototype.on.call(T.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",x),r.Factory.addGetterSetter(T,"stroke",void 0,(0,o.getStringOrGradientValidator)()),r.Factory.addGetterSetter(T,"strokeWidth",2,(0,o.getNumberValidator)()),r.Factory.addGetterSetter(T,"fillAfterStrokeEnabled",!1),r.Factory.addGetterSetter(T,"hitStrokeWidth","auto",(0,o.getNumberOrAutoValidator)()),r.Factory.addGetterSetter(T,"strokeHitEnabled",!0,(0,o.getBooleanValidator)()),r.Factory.addGetterSetter(T,"perfectDrawEnabled",!0,(0,o.getBooleanValidator)()),r.Factory.addGetterSetter(T,"shadowForStrokeEnabled",!0,(0,o.getBooleanValidator)()),r.Factory.addGetterSetter(T,"lineJoin"),r.Factory.addGetterSetter(T,"lineCap"),r.Factory.addGetterSetter(T,"sceneFunc"),r.Factory.addGetterSetter(T,"hitFunc"),r.Factory.addGetterSetter(T,"dash"),r.Factory.addGetterSetter(T,"dashOffset",0,(0,o.getNumberValidator)()),r.Factory.addGetterSetter(T,"shadowColor",void 0,(0,o.getStringValidator)()),r.Factory.addGetterSetter(T,"shadowBlur",0,(0,o.getNumberValidator)()),r.Factory.addGetterSetter(T,"shadowOpacity",1,(0,o.getNumberValidator)()),r.Factory.addComponentsGetterSetter(T,"shadowOffset",["x","y"]),r.Factory.addGetterSetter(T,"shadowOffsetX",0,(0,o.getNumberValidator)()),r.Factory.addGetterSetter(T,"shadowOffsetY",0,(0,o.getNumberValidator)()),r.Factory.addGetterSetter(T,"fillPatternImage"),r.Factory.addGetterSetter(T,"fill",void 0,(0,o.getStringOrGradientValidator)()),r.Factory.addGetterSetter(T,"fillPatternX",0,(0,o.getNumberValidator)()),r.Factory.addGetterSetter(T,"fillPatternY",0,(0,o.getNumberValidator)()),r.Factory.addGetterSetter(T,"fillLinearGradientColorStops"),r.Factory.addGetterSetter(T,"strokeLinearGradientColorStops"),r.Factory.addGetterSetter(T,"fillRadialGradientStartRadius",0),r.Factory.addGetterSetter(T,"fillRadialGradientEndRadius",0),r.Factory.addGetterSetter(T,"fillRadialGradientColorStops"),r.Factory.addGetterSetter(T,"fillPatternRepeat","repeat"),r.Factory.addGetterSetter(T,"fillEnabled",!0),r.Factory.addGetterSetter(T,"strokeEnabled",!0),r.Factory.addGetterSetter(T,"shadowEnabled",!0),r.Factory.addGetterSetter(T,"dashEnabled",!0),r.Factory.addGetterSetter(T,"strokeScaleEnabled",!0),r.Factory.addGetterSetter(T,"fillPriority","color"),r.Factory.addComponentsGetterSetter(T,"fillPatternOffset",["x","y"]),r.Factory.addGetterSetter(T,"fillPatternOffsetX",0,(0,o.getNumberValidator)()),r.Factory.addGetterSetter(T,"fillPatternOffsetY",0,(0,o.getNumberValidator)()),r.Factory.addComponentsGetterSetter(T,"fillPatternScale",["x","y"]),r.Factory.addGetterSetter(T,"fillPatternScaleX",1,(0,o.getNumberValidator)()),r.Factory.addGetterSetter(T,"fillPatternScaleY",1,(0,o.getNumberValidator)()),r.Factory.addComponentsGetterSetter(T,"fillLinearGradientStartPoint",["x","y"]),r.Factory.addComponentsGetterSetter(T,"strokeLinearGradientStartPoint",["x","y"]),r.Factory.addGetterSetter(T,"fillLinearGradientStartPointX",0),r.Factory.addGetterSetter(T,"strokeLinearGradientStartPointX",0),r.Factory.addGetterSetter(T,"fillLinearGradientStartPointY",0),r.Factory.addGetterSetter(T,"strokeLinearGradientStartPointY",0),r.Factory.addComponentsGetterSetter(T,"fillLinearGradientEndPoint",["x","y"]),r.Factory.addComponentsGetterSetter(T,"strokeLinearGradientEndPoint",["x","y"]),r.Factory.addGetterSetter(T,"fillLinearGradientEndPointX",0),r.Factory.addGetterSetter(T,"strokeLinearGradientEndPointX",0),r.Factory.addGetterSetter(T,"fillLinearGradientEndPointY",0),r.Factory.addGetterSetter(T,"strokeLinearGradientEndPointY",0),r.Factory.addComponentsGetterSetter(T,"fillRadialGradientStartPoint",["x","y"]),r.Factory.addGetterSetter(T,"fillRadialGradientStartPointX",0),r.Factory.addGetterSetter(T,"fillRadialGradientStartPointY",0),r.Factory.addComponentsGetterSetter(T,"fillRadialGradientEndPoint",["x","y"]),r.Factory.addGetterSetter(T,"fillRadialGradientEndPointX",0),r.Factory.addGetterSetter(T,"fillRadialGradientEndPointY",0),r.Factory.addGetterSetter(T,"fillPatternRotation",0),r.Factory.addGetterSetter(T,"fillRule",void 0,(0,o.getStringValidator)()),r.Factory.backCompat(T,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"})})(sn);Object.defineProperty(kh,"__esModule",{value:!0});kh.Layer=void 0;const go=Rt,Gb=gl,Ul=wt,wC=Te,i6=_i,tde=de,nde=sn,rde=Pe;var ide="#",ode="beforeDraw",sde="draw",fN=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],ade=fN.length;class vc extends Gb.Container{constructor(t){super(t),this.canvas=new i6.SceneCanvas,this.hitCanvas=new i6.HitCanvas({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(t){return this.getContext().clear(t),this.getHitCanvas().getContext().clear(t),this}setZIndex(t){super.setZIndex(t);var n=this.getStage();return n&&n.content&&(n.content.removeChild(this.getNativeCanvasElement()),t{this.draw(),this._waitingForDraw=!1})),this}getIntersection(t){if(!this.isListening()||!this.isVisible())return null;for(var n=1,r=!1;;){for(let i=0;i0)return{antialiased:!0};return{}}drawScene(t,n){var r=this.getLayer(),i=t||r&&r.getCanvas();return this._fire(ode,{node:this}),this.clearBeforeDraw()&&i.getContext().clear(),Gb.Container.prototype.drawScene.call(this,i,n),this._fire(sde,{node:this}),this}drawHit(t,n){var r=this.getLayer(),i=t||r&&r.hitCanvas;return r&&r.clearBeforeDraw()&&r.getHitCanvas().getContext().clear(),Gb.Container.prototype.drawHit.call(this,i,n),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){go.Util.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return go.Util.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!(!this.parent||!this.parent.content)){var t=this.parent,n=!!this.hitCanvas._canvas.parentNode;n?t.content.removeChild(this.hitCanvas._canvas):t.content.appendChild(this.hitCanvas._canvas)}}destroy(){return go.Util.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}}kh.Layer=vc;vc.prototype.nodeType="Layer";(0,rde._registerNode)(vc);wC.Factory.addGetterSetter(vc,"imageSmoothingEnabled",!0);wC.Factory.addGetterSetter(vc,"clearBeforeDraw",!0);wC.Factory.addGetterSetter(vc,"hitGraphEnabled",!0,(0,tde.getBooleanValidator)());var av={};Object.defineProperty(av,"__esModule",{value:!0});av.FastLayer=void 0;const lde=Rt,ude=kh,cde=Pe;class xC extends ude.Layer{constructor(t){super(t),this.listening(!1),lde.Util.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}av.FastLayer=xC;xC.prototype.nodeType="FastLayer";(0,cde._registerNode)(xC);var bc={};Object.defineProperty(bc,"__esModule",{value:!0});bc.Group=void 0;const dde=Rt,fde=gl,hde=Pe;class CC extends fde.Container{_validateAdd(t){var n=t.getType();n!=="Group"&&n!=="Shape"&&dde.Util.throw("You may only add groups and shapes to groups.")}}bc.Group=CC;CC.prototype.nodeType="Group";(0,hde._registerNode)(CC);var Sc={};Object.defineProperty(Sc,"__esModule",{value:!0});Sc.Animation=void 0;const Hb=Pe,o6=Rt;var qb=function(){return Hb.glob.performance&&Hb.glob.performance.now?function(){return Hb.glob.performance.now()}:function(){return new Date().getTime()}}();class Gi{constructor(t,n){this.id=Gi.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:qb(),frameRate:0},this.func=t,this.setLayers(n)}setLayers(t){var n=[];return t?t.length>0?n=t:n=[t]:n=[],this.layers=n,this}getLayers(){return this.layers}addLayer(t){var n=this.layers,r=n.length,i;for(i=0;ithis.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():p<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=p,this.update())}getTime(){return this._time}setPosition(p){this.prevPos=this._pos,this.propFunc(p),this._pos=p}getPosition(p){return p===void 0&&(p=this._time),this.func(p,this.begin,this._change,this.duration)}play(){this.state=a,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=l,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(p){this.pause(),this._time=p,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){var p=this.getTimer()-this._startTime;this.state===a?this.setTime(p):this.state===l&&this.setTime(this.duration-p)}pause(){this.state=s,this.fire("onPause")}getTimer(){return new Date().getTime()}}class f{constructor(p){var m=this,S=p.node,v=S._id,y,g=p.easing||e.Easings.Linear,b=!!p.yoyo,_;typeof p.duration>"u"?y=.3:p.duration===0?y=.001:y=p.duration,this.node=S,this._id=u++;var w=S.getLayer()||(S instanceof i.Konva.Stage?S.getLayers():null);w||t.Util.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new n.Animation(function(){m.tween.onEnterFrame()},w),this.tween=new d(_,function(x){m._tweenFunc(x)},g,0,1,y*1e3,b),this._addListeners(),f.attrs[v]||(f.attrs[v]={}),f.attrs[v][this._id]||(f.attrs[v][this._id]={}),f.tweens[v]||(f.tweens[v]={});for(_ in p)o[_]===void 0&&this._addAttr(_,p[_]);this.reset(),this.onFinish=p.onFinish,this.onReset=p.onReset,this.onUpdate=p.onUpdate}_addAttr(p,m){var S=this.node,v=S._id,y,g,b,_,w,x,T,P;if(b=f.tweens[v][p],b&&delete f.attrs[v][b][p],y=S.getAttr(p),t.Util._isArray(m))if(g=[],w=Math.max(m.length,y.length),p==="points"&&m.length!==y.length&&(m.length>y.length?(T=y,y=t.Util._prepareArrayForTween(y,m,S.closed())):(x=m,m=t.Util._prepareArrayForTween(m,y,S.closed()))),p.indexOf("fill")===0)for(_=0;_{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{var p=this.node,m=f.attrs[p._id][this._id];m.points&&m.points.trueEnd&&p.setAttr("points",m.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{var p=this.node,m=f.attrs[p._id][this._id];m.points&&m.points.trueStart&&p.points(m.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(p){return this.tween.seek(p*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){var p=this.node._id,m=this._id,S=f.tweens[p],v;this.pause();for(v in S)delete f.tweens[p][v];delete f.attrs[p][m]}}e.Tween=f,f.attrs={},f.tweens={},r.Node.prototype.to=function(h){var p=h.onFinish;h.node=this,h.onFinish=function(){this.destroy(),p&&p()};var m=new f(h);m.play()},e.Easings={BackEaseIn(h,p,m,S){var v=1.70158;return m*(h/=S)*h*((v+1)*h-v)+p},BackEaseOut(h,p,m,S){var v=1.70158;return m*((h=h/S-1)*h*((v+1)*h+v)+1)+p},BackEaseInOut(h,p,m,S){var v=1.70158;return(h/=S/2)<1?m/2*(h*h*(((v*=1.525)+1)*h-v))+p:m/2*((h-=2)*h*(((v*=1.525)+1)*h+v)+2)+p},ElasticEaseIn(h,p,m,S,v,y){var g=0;return h===0?p:(h/=S)===1?p+m:(y||(y=S*.3),!v||v0?t:n),c=s*n,d=a*(a>0?t:n),f=l*(l>0?n:t);return{x:u,y:r?-1*f:d,width:c-u,height:f-d}}}lv.Arc=Yo;Yo.prototype._centroid=!0;Yo.prototype.className="Arc";Yo.prototype._attrsAffectingSize=["innerRadius","outerRadius"];(0,gde._registerNode)(Yo);uv.Factory.addGetterSetter(Yo,"innerRadius",0,(0,cv.getNumberValidator)());uv.Factory.addGetterSetter(Yo,"outerRadius",0,(0,cv.getNumberValidator)());uv.Factory.addGetterSetter(Yo,"angle",0,(0,cv.getNumberValidator)());uv.Factory.addGetterSetter(Yo,"clockwise",!1,(0,cv.getBooleanValidator)());var dv={},Oh={};Object.defineProperty(Oh,"__esModule",{value:!0});Oh.Line=void 0;const fv=Te,mde=sn,pN=de,yde=Pe;function v2(e,t,n,r,i,o,s){var a=Math.sqrt(Math.pow(n-e,2)+Math.pow(r-t,2)),l=Math.sqrt(Math.pow(i-n,2)+Math.pow(o-r,2)),u=s*a/(a+l),c=s*l/(a+l),d=n-u*(i-e),f=r-u*(o-t),h=n+c*(i-e),p=r+c*(o-t);return[d,f,h,p]}function a6(e,t){var n=e.length,r=[],i,o;for(i=2;i4){for(a=this.getTensionPoints(),l=a.length,u=o?0:4,o||t.quadraticCurveTo(a[0],a[1],a[2],a[3]);u{let u,c,d;u=l/2,c=0;for(let h=0;h<20;h++)d=u*e.tValues[20][h]+u,c+=e.cValues[20][h]*r(s,a,d);return u*c};e.getCubicArcLength=t;const n=(s,a,l)=>{l===void 0&&(l=1);const u=s[0]-2*s[1]+s[2],c=a[0]-2*a[1]+a[2],d=2*s[1]-2*s[0],f=2*a[1]-2*a[0],h=4*(u*u+c*c),p=4*(u*d+c*f),m=d*d+f*f;if(h===0)return l*Math.sqrt(Math.pow(s[2]-s[0],2)+Math.pow(a[2]-a[0],2));const S=p/(2*h),v=m/h,y=l+S,g=v-S*S,b=y*y+g>0?Math.sqrt(y*y+g):0,_=S*S+g>0?Math.sqrt(S*S+g):0,w=S+Math.sqrt(S*S+g)!==0?g*Math.log(Math.abs((y+b)/(S+_))):0;return Math.sqrt(h)/2*(y*b-S*_+w)};e.getQuadraticArcLength=n;function r(s,a,l){const u=i(1,l,s),c=i(1,l,a),d=u*u+c*c;return Math.sqrt(d)}const i=(s,a,l)=>{const u=l.length-1;let c,d;if(u===0)return 0;if(s===0){d=0;for(let f=0;f<=u;f++)d+=e.binomialCoefficients[u][f]*Math.pow(1-a,u-f)*Math.pow(a,f)*l[f];return d}else{c=new Array(u);for(let f=0;f{let u=1,c=s/a,d=(s-l(c))/a,f=0;for(;u>.001;){const h=l(c+d),p=Math.abs(s-h)/a;if(p500)break}return c};e.t2length=o})(gN);Object.defineProperty(_c,"__esModule",{value:!0});_c.Path=void 0;const vde=Te,bde=sn,Sde=Pe,Gl=gN;class Jt extends bde.Shape{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=Jt.parsePathData(this.data()),this.pathLength=Jt.getPathLength(this.dataArray)}_sceneFunc(t){var n=this.dataArray;t.beginPath();for(var r=!1,i=0;ic?u:c,S=u>c?1:u/c,v=u>c?c/u:1;t.translate(a,l),t.rotate(h),t.scale(S,v),t.arc(0,0,m,d,d+f,1-p),t.scale(1/S,1/v),t.rotate(-h),t.translate(-a,-l);break;case"z":r=!0,t.closePath();break}}!r&&!this.hasFill()?t.strokeShape(this):t.fillStrokeShape(this)}getSelfRect(){var t=[];this.dataArray.forEach(function(u){if(u.command==="A"){var c=u.points[4],d=u.points[5],f=u.points[4]+d,h=Math.PI/180;if(Math.abs(c-f)f;p-=h){const m=Jt.getPointOnEllipticalArc(u.points[0],u.points[1],u.points[2],u.points[3],p,0);t.push(m.x,m.y)}else for(let p=c+h;pn[i].pathLength;)t-=n[i].pathLength,++i;if(i===o)return r=n[i-1].points.slice(-2),{x:r[0],y:r[1]};if(t<.01)return r=n[i].points.slice(0,2),{x:r[0],y:r[1]};var s=n[i],a=s.points;switch(s.command){case"L":return Jt.getPointOnLine(t,s.start.x,s.start.y,a[0],a[1]);case"C":return Jt.getPointOnCubicBezier((0,Gl.t2length)(t,Jt.getPathLength(n),m=>(0,Gl.getCubicArcLength)([s.start.x,a[0],a[2],a[4]],[s.start.y,a[1],a[3],a[5]],m)),s.start.x,s.start.y,a[0],a[1],a[2],a[3],a[4],a[5]);case"Q":return Jt.getPointOnQuadraticBezier((0,Gl.t2length)(t,Jt.getPathLength(n),m=>(0,Gl.getQuadraticArcLength)([s.start.x,a[0],a[2]],[s.start.y,a[1],a[3]],m)),s.start.x,s.start.y,a[0],a[1],a[2],a[3]);case"A":var l=a[0],u=a[1],c=a[2],d=a[3],f=a[4],h=a[5],p=a[6];return f+=h*t/s.pathLength,Jt.getPointOnEllipticalArc(l,u,c,d,f,p)}return null}static getPointOnLine(t,n,r,i,o,s,a){s===void 0&&(s=n),a===void 0&&(a=r);var l=(o-r)/(i-n+1e-8),u=Math.sqrt(t*t/(1+l*l));i0&&!isNaN(p[0]);){var y=null,g=[],b=l,_=u,w,x,T,P,E,A,$,M,C,O;switch(h){case"l":l+=p.shift(),u+=p.shift(),y="L",g.push(l,u);break;case"L":l=p.shift(),u=p.shift(),g.push(l,u);break;case"m":var I=p.shift(),N=p.shift();if(l+=I,u+=N,y="M",s.length>2&&s[s.length-1].command==="z"){for(var R=s.length-2;R>=0;R--)if(s[R].command==="M"){l=s[R].points[0]+I,u=s[R].points[1]+N;break}}g.push(l,u),h="l";break;case"M":l=p.shift(),u=p.shift(),y="M",g.push(l,u),h="L";break;case"h":l+=p.shift(),y="L",g.push(l,u);break;case"H":l=p.shift(),y="L",g.push(l,u);break;case"v":u+=p.shift(),y="L",g.push(l,u);break;case"V":u=p.shift(),y="L",g.push(l,u);break;case"C":g.push(p.shift(),p.shift(),p.shift(),p.shift()),l=p.shift(),u=p.shift(),g.push(l,u);break;case"c":g.push(l+p.shift(),u+p.shift(),l+p.shift(),u+p.shift()),l+=p.shift(),u+=p.shift(),y="C",g.push(l,u);break;case"S":x=l,T=u,w=s[s.length-1],w.command==="C"&&(x=l+(l-w.points[2]),T=u+(u-w.points[3])),g.push(x,T,p.shift(),p.shift()),l=p.shift(),u=p.shift(),y="C",g.push(l,u);break;case"s":x=l,T=u,w=s[s.length-1],w.command==="C"&&(x=l+(l-w.points[2]),T=u+(u-w.points[3])),g.push(x,T,l+p.shift(),u+p.shift()),l+=p.shift(),u+=p.shift(),y="C",g.push(l,u);break;case"Q":g.push(p.shift(),p.shift()),l=p.shift(),u=p.shift(),g.push(l,u);break;case"q":g.push(l+p.shift(),u+p.shift()),l+=p.shift(),u+=p.shift(),y="Q",g.push(l,u);break;case"T":x=l,T=u,w=s[s.length-1],w.command==="Q"&&(x=l+(l-w.points[0]),T=u+(u-w.points[1])),l=p.shift(),u=p.shift(),y="Q",g.push(x,T,l,u);break;case"t":x=l,T=u,w=s[s.length-1],w.command==="Q"&&(x=l+(l-w.points[0]),T=u+(u-w.points[1])),l+=p.shift(),u+=p.shift(),y="Q",g.push(x,T,l,u);break;case"A":P=p.shift(),E=p.shift(),A=p.shift(),$=p.shift(),M=p.shift(),C=l,O=u,l=p.shift(),u=p.shift(),y="A",g=this.convertEndpointToCenterParameterization(C,O,l,u,$,M,P,E,A);break;case"a":P=p.shift(),E=p.shift(),A=p.shift(),$=p.shift(),M=p.shift(),C=l,O=u,l+=p.shift(),u+=p.shift(),y="A",g=this.convertEndpointToCenterParameterization(C,O,l,u,$,M,P,E,A);break}s.push({command:y||h,points:g,start:{x:b,y:_},pathLength:this.calcLength(b,_,y||h,g)})}(h==="z"||h==="Z")&&s.push({command:"z",points:[],start:void 0,pathLength:0})}return s}static calcLength(t,n,r,i){var o,s,a,l,u=Jt;switch(r){case"L":return u.getLineLength(t,n,i[0],i[1]);case"C":return(0,Gl.getCubicArcLength)([t,i[0],i[2],i[4]],[n,i[1],i[3],i[5]],1);case"Q":return(0,Gl.getQuadraticArcLength)([t,i[0],i[2]],[n,i[1],i[3]],1);case"A":o=0;var c=i[4],d=i[5],f=i[4]+d,h=Math.PI/180;if(Math.abs(c-f)f;l-=h)a=u.getPointOnEllipticalArc(i[0],i[1],i[2],i[3],l,0),o+=u.getLineLength(s.x,s.y,a.x,a.y),s=a;else for(l=c+h;l1&&(a*=Math.sqrt(h),l*=Math.sqrt(h));var p=Math.sqrt((a*a*(l*l)-a*a*(f*f)-l*l*(d*d))/(a*a*(f*f)+l*l*(d*d)));o===s&&(p*=-1),isNaN(p)&&(p=0);var m=p*a*f/l,S=p*-l*d/a,v=(t+r)/2+Math.cos(c)*m-Math.sin(c)*S,y=(n+i)/2+Math.sin(c)*m+Math.cos(c)*S,g=function(E){return Math.sqrt(E[0]*E[0]+E[1]*E[1])},b=function(E,A){return(E[0]*A[0]+E[1]*A[1])/(g(E)*g(A))},_=function(E,A){return(E[0]*A[1]=1&&(P=0),s===0&&P>0&&(P=P-2*Math.PI),s===1&&P<0&&(P=P+2*Math.PI),[v,y,a,l,w,P,c,s]}}_c.Path=Jt;Jt.prototype.className="Path";Jt.prototype._attrsAffectingSize=["data"];(0,Sde._registerNode)(Jt);vde.Factory.addGetterSetter(Jt,"data");Object.defineProperty(dv,"__esModule",{value:!0});dv.Arrow=void 0;const hv=Te,_de=Oh,mN=de,wde=Pe,l6=_c;class yl extends _de.Line{_sceneFunc(t){super._sceneFunc(t);var n=Math.PI*2,r=this.points(),i=r,o=this.tension()!==0&&r.length>4;o&&(i=this.getTensionPoints());var s=this.pointerLength(),a=r.length,l,u;if(o){const f=[i[i.length-4],i[i.length-3],i[i.length-2],i[i.length-1],r[a-2],r[a-1]],h=l6.Path.calcLength(i[i.length-4],i[i.length-3],"C",f),p=l6.Path.getPointOnQuadraticBezier(Math.min(1,1-s/h),f[0],f[1],f[2],f[3],f[4],f[5]);l=r[a-2]-p.x,u=r[a-1]-p.y}else l=r[a-2]-r[a-4],u=r[a-1]-r[a-3];var c=(Math.atan2(u,l)+n)%n,d=this.pointerWidth();this.pointerAtEnding()&&(t.save(),t.beginPath(),t.translate(r[a-2],r[a-1]),t.rotate(c),t.moveTo(0,0),t.lineTo(-s,d/2),t.lineTo(-s,-d/2),t.closePath(),t.restore(),this.__fillStroke(t)),this.pointerAtBeginning()&&(t.save(),t.beginPath(),t.translate(r[0],r[1]),o?(l=(i[0]+i[2])/2-r[0],u=(i[1]+i[3])/2-r[1]):(l=r[2]-r[0],u=r[3]-r[1]),t.rotate((Math.atan2(-u,-l)+n)%n),t.moveTo(0,0),t.lineTo(-s,d/2),t.lineTo(-s,-d/2),t.closePath(),t.restore(),this.__fillStroke(t))}__fillStroke(t){var n=this.dashEnabled();n&&(this.attrs.dashEnabled=!1,t.setLineDash([])),t.fillStrokeShape(this),n&&(this.attrs.dashEnabled=!0)}getSelfRect(){const t=super.getSelfRect(),n=this.pointerWidth()/2;return{x:t.x-n,y:t.y-n,width:t.width+n*2,height:t.height+n*2}}}dv.Arrow=yl;yl.prototype.className="Arrow";(0,wde._registerNode)(yl);hv.Factory.addGetterSetter(yl,"pointerLength",10,(0,mN.getNumberValidator)());hv.Factory.addGetterSetter(yl,"pointerWidth",10,(0,mN.getNumberValidator)());hv.Factory.addGetterSetter(yl,"pointerAtBeginning",!1);hv.Factory.addGetterSetter(yl,"pointerAtEnding",!0);var pv={};Object.defineProperty(pv,"__esModule",{value:!0});pv.Circle=void 0;const xde=Te,Cde=sn,Tde=de,Ede=Pe;let wc=class extends Cde.Shape{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius()!==t/2&&this.radius(t/2)}setHeight(t){this.radius()!==t/2&&this.radius(t/2)}};pv.Circle=wc;wc.prototype._centroid=!0;wc.prototype.className="Circle";wc.prototype._attrsAffectingSize=["radius"];(0,Ede._registerNode)(wc);xde.Factory.addGetterSetter(wc,"radius",0,(0,Tde.getNumberValidator)());var gv={};Object.defineProperty(gv,"__esModule",{value:!0});gv.Ellipse=void 0;const TC=Te,Pde=sn,yN=de,Ade=Pe;class oa extends Pde.Shape{_sceneFunc(t){var n=this.radiusX(),r=this.radiusY();t.beginPath(),t.save(),n!==r&&t.scale(1,r/n),t.arc(0,0,n,0,Math.PI*2,!1),t.restore(),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(t){this.radiusX(t/2)}setHeight(t){this.radiusY(t/2)}}gv.Ellipse=oa;oa.prototype.className="Ellipse";oa.prototype._centroid=!0;oa.prototype._attrsAffectingSize=["radiusX","radiusY"];(0,Ade._registerNode)(oa);TC.Factory.addComponentsGetterSetter(oa,"radius",["x","y"]);TC.Factory.addGetterSetter(oa,"radiusX",0,(0,yN.getNumberValidator)());TC.Factory.addGetterSetter(oa,"radiusY",0,(0,yN.getNumberValidator)());var mv={};Object.defineProperty(mv,"__esModule",{value:!0});mv.Image=void 0;const Wb=Rt,vl=Te,kde=sn,Ode=Pe,Rh=de;let ao=class vN extends kde.Shape{constructor(t){super(t),this.on("imageChange.konva",()=>{this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const t=this.image();t&&t.complete||t&&t.readyState===4||t&&t.addEventListener&&t.addEventListener("load",()=>{this._requestDraw()})}_useBufferCanvas(){return super._useBufferCanvas(!0)}_sceneFunc(t){const n=this.getWidth(),r=this.getHeight(),i=this.cornerRadius(),o=this.attrs.image;let s;if(o){const a=this.attrs.cropWidth,l=this.attrs.cropHeight;a&&l?s=[o,this.cropX(),this.cropY(),a,l,0,0,n,r]:s=[o,0,0,n,r]}(this.hasFill()||this.hasStroke()||i)&&(t.beginPath(),i?Wb.Util.drawRoundedRectPath(t,n,r,i):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)),o&&(i&&t.clip(),t.drawImage.apply(t,s))}_hitFunc(t){var n=this.width(),r=this.height(),i=this.cornerRadius();t.beginPath(),i?Wb.Util.drawRoundedRectPath(t,n,r,i):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}getWidth(){var t,n;return(t=this.attrs.width)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.width}getHeight(){var t,n;return(t=this.attrs.height)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.height}static fromURL(t,n,r=null){var i=Wb.Util.createImageElement();i.onload=function(){var o=new vN({image:i});n(o)},i.onerror=r,i.crossOrigin="Anonymous",i.src=t}};mv.Image=ao;ao.prototype.className="Image";(0,Ode._registerNode)(ao);vl.Factory.addGetterSetter(ao,"cornerRadius",0,(0,Rh.getNumberOrArrayOfNumbersValidator)(4));vl.Factory.addGetterSetter(ao,"image");vl.Factory.addComponentsGetterSetter(ao,"crop",["x","y","width","height"]);vl.Factory.addGetterSetter(ao,"cropX",0,(0,Rh.getNumberValidator)());vl.Factory.addGetterSetter(ao,"cropY",0,(0,Rh.getNumberValidator)());vl.Factory.addGetterSetter(ao,"cropWidth",0,(0,Rh.getNumberValidator)());vl.Factory.addGetterSetter(ao,"cropHeight",0,(0,Rh.getNumberValidator)());var oc={};Object.defineProperty(oc,"__esModule",{value:!0});oc.Tag=oc.Label=void 0;const yv=Te,Rde=sn,Ide=bc,EC=de,bN=Pe;var SN=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],Mde="Change.konva",Nde="none",b2="up",S2="right",_2="down",w2="left",Dde=SN.length;class PC extends Ide.Group{constructor(t){super(t),this.on("add.konva",function(n){this._addListeners(n.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(t){var n=this,r,i=function(){n._sync()};for(r=0;r{n=Math.min(n,s.x),r=Math.max(r,s.x),i=Math.min(i,s.y),o=Math.max(o,s.y)}),{x:n,y:i,width:r-n,height:o-i}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}bv.RegularPolygon=Sl;Sl.prototype.className="RegularPolygon";Sl.prototype._centroid=!0;Sl.prototype._attrsAffectingSize=["radius"];(0,zde._registerNode)(Sl);_N.Factory.addGetterSetter(Sl,"radius",0,(0,wN.getNumberValidator)());_N.Factory.addGetterSetter(Sl,"sides",0,(0,wN.getNumberValidator)());var Sv={};Object.defineProperty(Sv,"__esModule",{value:!0});Sv.Ring=void 0;const xN=Te,Ude=sn,CN=de,Gde=Pe;var u6=Math.PI*2;class _l extends Ude.Shape{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,u6,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),u6,0,!0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(t){this.outerRadius(t/2)}setHeight(t){this.outerRadius(t/2)}}Sv.Ring=_l;_l.prototype.className="Ring";_l.prototype._centroid=!0;_l.prototype._attrsAffectingSize=["innerRadius","outerRadius"];(0,Gde._registerNode)(_l);xN.Factory.addGetterSetter(_l,"innerRadius",0,(0,CN.getNumberValidator)());xN.Factory.addGetterSetter(_l,"outerRadius",0,(0,CN.getNumberValidator)());var _v={};Object.defineProperty(_v,"__esModule",{value:!0});_v.Sprite=void 0;const wl=Te,Hde=sn,qde=Sc,TN=de,Wde=Pe;class lo extends Hde.Shape{constructor(t){super(t),this._updated=!0,this.anim=new qde.Animation(()=>{var n=this._updated;return this._updated=!1,n}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(t){var n=this.animation(),r=this.frameIndex(),i=r*4,o=this.animations()[n],s=this.frameOffsets(),a=o[i+0],l=o[i+1],u=o[i+2],c=o[i+3],d=this.image();if((this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,u,c),t.closePath(),t.fillStrokeShape(this)),d)if(s){var f=s[n],h=r*2;t.drawImage(d,a,l,u,c,f[h+0],f[h+1],u,c)}else t.drawImage(d,a,l,u,c,0,0,u,c)}_hitFunc(t){var n=this.animation(),r=this.frameIndex(),i=r*4,o=this.animations()[n],s=this.frameOffsets(),a=o[i+2],l=o[i+3];if(t.beginPath(),s){var u=s[n],c=r*2;t.rect(u[c+0],u[c+1],a,l)}else t.rect(0,0,a,l);t.closePath(),t.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){var t=this;this.interval=setInterval(function(){t._updateIndex()},1e3/this.frameRate())}start(){if(!this.isRunning()){var t=this.getLayer();this.anim.setLayers(t),this._setInterval(),this.anim.start()}}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){var t=this.frameIndex(),n=this.animation(),r=this.animations(),i=r[n],o=i.length/4;t{t=t.trim();const n=t.indexOf(" ")>=0,r=t.indexOf('"')>=0||t.indexOf("'")>=0;return n&&!r&&(t=`"${t}"`),t}).join(", ")}var Fp;function Xb(){return Fp||(Fp=x2.Util.createCanvasElement().getContext(efe),Fp)}function dfe(e){e.fillText(this._partialText,this._partialTextX,this._partialTextY)}function ffe(e){e.setAttr("miterLimit",2),e.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function hfe(e){return e=e||{},!e.fillLinearGradientColorStops&&!e.fillRadialGradientColorStops&&!e.fillPatternImage&&(e.fill=e.fill||"black"),e}class Ut extends Yde.Shape{constructor(t){super(hfe(t)),this._partialTextX=0,this._partialTextY=0;for(var n=0;n1&&(v+=s)}}}_hitFunc(t){var n=this.getWidth(),r=this.getHeight();t.beginPath(),t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}setText(t){var n=x2.Util._isString(t)?t:t==null?"":t+"";return this._setAttr(tfe,n),this}getWidth(){var t=this.attrs.width===Hl||this.attrs.width===void 0;return t?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){var t=this.attrs.height===Hl||this.attrs.height===void 0;return t?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return x2.Util.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(t){var n=Xb(),r=this.fontSize(),i;return n.save(),n.font=this._getContextFont(),i=n.measureText(t),n.restore(),{width:i.width,height:r}}_getContextFont(){return this.fontStyle()+$p+this.fontVariant()+$p+(this.fontSize()+ofe)+cfe(this.fontFamily())}_addTextLine(t){this.align()===Jc&&(t=t.trim());var r=this._getTextWidth(t);return this.textArr.push({text:t,width:r,lastInParagraph:!1})}_getTextWidth(t){var n=this.letterSpacing(),r=t.length;return Xb().measureText(t).width+(r?n*(r-1):0)}_setTextData(){var t=this.text().split(` +`),n=+this.fontSize(),r=0,i=this.lineHeight()*n,o=this.attrs.width,s=this.attrs.height,a=o!==Hl&&o!==void 0,l=s!==Hl&&s!==void 0,u=this.padding(),c=o-u*2,d=s-u*2,f=0,h=this.wrap(),p=h!==f6,m=h!==lfe&&p,S=this.ellipsis();this.textArr=[],Xb().font=this._getContextFont();for(var v=S?this._getTextWidth(Kb):0,y=0,g=t.length;yc)for(;b.length>0;){for(var w=0,x=b.length,T="",P=0;w>>1,A=b.slice(0,E+1),$=this._getTextWidth(A)+v;$<=c?(w=E+1,T=A,P=$):x=E}if(T){if(m){var M,C=b[T.length],O=C===$p||C===c6;O&&P<=c?M=T.length:M=Math.max(T.lastIndexOf($p),T.lastIndexOf(c6))+1,M>0&&(w=M,T=T.slice(0,w),P=this._getTextWidth(T))}T=T.trimRight(),this._addTextLine(T),r=Math.max(r,P),f+=i;var I=this._shouldHandleEllipsis(f);if(I){this._tryToAddEllipsisToLastLine();break}if(b=b.slice(w),b=b.trimLeft(),b.length>0&&(_=this._getTextWidth(b),_<=c)){this._addTextLine(b),f+=i,r=Math.max(r,_);break}}else break}else this._addTextLine(b),f+=i,r=Math.max(r,_),this._shouldHandleEllipsis(f)&&yd)break}this.textHeight=n,this.textWidth=r}_shouldHandleEllipsis(t){var n=+this.fontSize(),r=this.lineHeight()*n,i=this.attrs.height,o=i!==Hl&&i!==void 0,s=this.padding(),a=i-s*2,l=this.wrap(),u=l!==f6;return!u||o&&t+r>a}_tryToAddEllipsisToLastLine(){var t=this.attrs.width,n=t!==Hl&&t!==void 0,r=this.padding(),i=t-r*2,o=this.ellipsis(),s=this.textArr[this.textArr.length-1];if(!(!s||!o)){if(n){var a=this._getTextWidth(s.text+Kb)n?null:ed.Path.getPointAtLengthOfDataArray(t,this.dataArray)}_readDataAttribute(){this.dataArray=ed.Path.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(t){t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",this.textBaseline()),t.setAttr("textAlign","left"),t.save();var n=this.textDecoration(),r=this.fill(),i=this.fontSize(),o=this.glyphInfo;n==="underline"&&t.beginPath();for(var s=0;s=1){var r=n[0].p0;t.moveTo(r.x,r.y)}for(var i=0;ie+`.${NN}`).join(" "),g6="nodesRect",_fe=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange"],wfe={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135};const xfe="ontouchstart"in si.Konva._global;function Cfe(e,t){if(e==="rotater")return"crosshair";t+=Qe.Util.degToRad(wfe[e]||0);var n=(Qe.Util.radToDeg(t)%360+360)%360;return Qe.Util._inRange(n,315+22.5,360)||Qe.Util._inRange(n,0,22.5)?"ns-resize":Qe.Util._inRange(n,45-22.5,45+22.5)?"nesw-resize":Qe.Util._inRange(n,90-22.5,90+22.5)?"ew-resize":Qe.Util._inRange(n,135-22.5,135+22.5)?"nwse-resize":Qe.Util._inRange(n,180-22.5,180+22.5)?"ns-resize":Qe.Util._inRange(n,225-22.5,225+22.5)?"nesw-resize":Qe.Util._inRange(n,270-22.5,270+22.5)?"ew-resize":Qe.Util._inRange(n,315-22.5,315+22.5)?"nwse-resize":(Qe.Util.error("Transformer has unknown angle for cursor detection: "+n),"pointer")}var Qm=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],m6=1e8;function Tfe(e){return{x:e.x+e.width/2*Math.cos(e.rotation)+e.height/2*Math.sin(-e.rotation),y:e.y+e.height/2*Math.cos(e.rotation)+e.width/2*Math.sin(e.rotation)}}function DN(e,t,n){const r=n.x+(e.x-n.x)*Math.cos(t)-(e.y-n.y)*Math.sin(t),i=n.y+(e.x-n.x)*Math.sin(t)+(e.y-n.y)*Math.cos(t);return Object.assign(Object.assign({},e),{rotation:e.rotation+t,x:r,y:i})}function Efe(e,t){const n=Tfe(e);return DN(e,t,n)}function Pfe(e,t,n){let r=t;for(let i=0;ii.isAncestorOf(this)?(Qe.Util.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);this._nodes=t=n,t.length===1&&this.useSingleNodeRotation()?this.rotation(t[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(i=>{const o=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()},s=i._attrsAffectingSize.map(a=>a+"Change."+this._getEventNamespace()).join(" ");i.on(s,o),i.on(_fe.map(a=>a+`.${this._getEventNamespace()}`).join(" "),o),i.on(`absoluteTransformChange.${this._getEventNamespace()}`,o),this._proxyDrag(i)}),this._resetTransformCache();var r=!!this.findOne(".top-left");return r&&this.update(),this}_proxyDrag(t){let n;t.on(`dragstart.${this._getEventNamespace()}`,r=>{n=t.getAbsolutePosition(),!this.isDragging()&&t!==this.findOne(".back")&&this.startDrag(r,!1)}),t.on(`dragmove.${this._getEventNamespace()}`,r=>{if(!n)return;const i=t.getAbsolutePosition(),o=i.x-n.x,s=i.y-n.y;this.nodes().forEach(a=>{if(a===t||a.isDragging())return;const l=a.getAbsolutePosition();a.setAbsolutePosition({x:l.x+o,y:l.y+s}),a.startDrag(r)}),n=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(t=>{t.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(g6),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(g6,this.__getNodeRect)}__getNodeShape(t,n=this.rotation(),r){var i=t.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),o=t.getAbsoluteScale(r),s=t.getAbsolutePosition(r),a=i.x*o.x-t.offsetX()*o.x,l=i.y*o.y-t.offsetY()*o.y;const u=(si.Konva.getAngle(t.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),c={x:s.x+a*Math.cos(u)+l*Math.sin(-u),y:s.y+l*Math.cos(u)+a*Math.sin(u),width:i.width*o.x,height:i.height*o.y,rotation:u};return DN(c,-si.Konva.getAngle(n),{x:0,y:0})}__getNodeRect(){var t=this.getNode();if(!t)return{x:-m6,y:-m6,width:0,height:0,rotation:0};const n=[];this.nodes().map(u=>{const c=u.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()});var d=[{x:c.x,y:c.y},{x:c.x+c.width,y:c.y},{x:c.x+c.width,y:c.y+c.height},{x:c.x,y:c.y+c.height}],f=u.getAbsoluteTransform();d.forEach(function(h){var p=f.point(h);n.push(p)})});const r=new Qe.Transform;r.rotate(-si.Konva.getAngle(this.rotation()));var i,o,s,a;n.forEach(function(u){var c=r.point(u);i===void 0&&(i=s=c.x,o=a=c.y),i=Math.min(i,c.x),o=Math.min(o,c.y),s=Math.max(s,c.x),a=Math.max(a,c.y)}),r.invert();const l=r.point({x:i,y:o});return{x:l.x,y:l.y,width:s-i,height:a-o,rotation:si.Konva.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),Qm.forEach((function(t){this._createAnchor(t)}).bind(this)),this._createAnchor("rotater")}_createAnchor(t){var n=new vfe.Rect({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:xfe?10:"auto"}),r=this;n.on("mousedown touchstart",function(i){r._handleMouseDown(i)}),n.on("dragstart",i=>{n.stopDrag(),i.cancelBubble=!0}),n.on("dragend",i=>{i.cancelBubble=!0}),n.on("mouseenter",()=>{var i=si.Konva.getAngle(this.rotation()),o=Cfe(t,i);n.getStage().content&&(n.getStage().content.style.cursor=o),this._cursorChange=!0}),n.on("mouseout",()=>{n.getStage().content&&(n.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(n)}_createBack(){var t=new yfe.Shape({name:"back",width:0,height:0,draggable:!0,sceneFunc(n){var r=this.getParent(),i=r.padding();n.beginPath(),n.rect(-i,-i,this.width()+i*2,this.height()+i*2),n.moveTo(this.width()/2,-i),r.rotateEnabled()&&n.lineTo(this.width()/2,-r.rotateAnchorOffset()*Qe.Util._sign(this.height())-i),n.fillStrokeShape(this)},hitFunc:(n,r)=>{if(this.shouldOverdrawWholeArea()){var i=this.padding();n.beginPath(),n.rect(-i,-i,r.width()+i*2,r.height()+i*2),n.fillStrokeShape(r)}}});this.add(t),this._proxyDrag(t),t.on("dragstart",n=>{n.cancelBubble=!0}),t.on("dragmove",n=>{n.cancelBubble=!0}),t.on("dragend",n=>{n.cancelBubble=!0}),this.on("dragmove",n=>{this.update()})}_handleMouseDown(t){this._movingAnchorName=t.target.name().split(" ")[0];var n=this._getNodeRect(),r=n.width,i=n.height,o=Math.sqrt(Math.pow(r,2)+Math.pow(i,2));this.sin=Math.abs(i/o),this.cos=Math.abs(r/o),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;var s=t.target.getAbsolutePosition(),a=t.target.getStage().getPointerPosition();this._anchorDragOffset={x:a.x-s.x,y:a.y-s.y},this._fire("transformstart",{evt:t.evt,target:this.getNode()}),this._nodes.forEach(l=>{l._fire("transformstart",{evt:t.evt,target:l})})}_handleMouseMove(t){var n,r,i,o=this.findOne("."+this._movingAnchorName),s=o.getStage();s.setPointersPositions(t);const a=s.getPointerPosition();let l={x:a.x-this._anchorDragOffset.x,y:a.y-this._anchorDragOffset.y};const u=o.getAbsolutePosition();this.anchorDragBoundFunc()&&(l=this.anchorDragBoundFunc()(u,l,t)),o.setAbsolutePosition(l);const c=o.getAbsolutePosition();if(!(u.x===c.x&&u.y===c.y)){if(this._movingAnchorName==="rotater"){var d=this._getNodeRect();n=o.x()-d.width/2,r=-o.y()+d.height/2;let M=Math.atan2(-r,n)+Math.PI/2;d.height<0&&(M-=Math.PI);var f=si.Konva.getAngle(this.rotation());const C=f+M,O=si.Konva.getAngle(this.rotationSnapTolerance()),N=Pfe(this.rotationSnaps(),C,O)-d.rotation,R=Efe(d,N);this._fitNodesInto(R,t);return}var h=this.shiftBehavior(),p;h==="inverted"?p=this.keepRatio()&&!t.shiftKey:h==="none"?p=this.keepRatio():p=this.keepRatio()||t.shiftKey;var g=this.centeredScaling()||t.altKey;if(this._movingAnchorName==="top-left"){if(p){var m=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};i=Math.sqrt(Math.pow(m.x-o.x(),2)+Math.pow(m.y-o.y(),2));var S=this.findOne(".top-left").x()>m.x?-1:1,v=this.findOne(".top-left").y()>m.y?-1:1;n=i*this.cos*S,r=i*this.sin*v,this.findOne(".top-left").x(m.x-n),this.findOne(".top-left").y(m.y-r)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(o.y());else if(this._movingAnchorName==="top-right"){if(p){var m=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};i=Math.sqrt(Math.pow(o.x()-m.x,2)+Math.pow(m.y-o.y(),2));var S=this.findOne(".top-right").x()m.y?-1:1;n=i*this.cos*S,r=i*this.sin*v,this.findOne(".top-right").x(m.x+n),this.findOne(".top-right").y(m.y-r)}var y=o.position();this.findOne(".top-left").y(y.y),this.findOne(".bottom-right").x(y.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(o.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(o.x());else if(this._movingAnchorName==="bottom-left"){if(p){var m=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};i=Math.sqrt(Math.pow(m.x-o.x(),2)+Math.pow(o.y()-m.y,2));var S=m.x{r._fire("transformend",{evt:t,target:r})}),this._movingAnchorName=null}}_fitNodesInto(t,n){var r=this._getNodeRect();const i=1;if(Qe.Util._inRange(t.width,-this.padding()*2-i,i)){this.update();return}if(Qe.Util._inRange(t.height,-this.padding()*2-i,i)){this.update();return}const o=this.flipEnabled();var s=new Qe.Transform;if(s.rotate(si.Konva.getAngle(this.rotation())),this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const d=s.point({x:-this.padding()*2,y:0});if(t.x+=d.x,t.y+=d.y,t.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=d.x,this._anchorDragOffset.y-=d.y,!o){this.update();return}}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const d=s.point({x:this.padding()*2,y:0});if(this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=d.x,this._anchorDragOffset.y-=d.y,t.width+=this.padding()*2,!o){this.update();return}}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const d=s.point({x:0,y:-this.padding()*2});if(t.x+=d.x,t.y+=d.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=d.x,this._anchorDragOffset.y-=d.y,t.height+=this.padding()*2,!o){this.update();return}}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const d=s.point({x:0,y:this.padding()*2});if(this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=d.x,this._anchorDragOffset.y-=d.y,t.height+=this.padding()*2,!o){this.update();return}}if(this.boundBoxFunc()){const d=this.boundBoxFunc()(r,t);d?t=d:Qe.Util.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const a=1e7,l=new Qe.Transform;l.translate(r.x,r.y),l.rotate(r.rotation),l.scale(r.width/a,r.height/a);const u=new Qe.Transform;u.translate(t.x,t.y),u.rotate(t.rotation),u.scale(t.width/a,t.height/a);const c=u.multiply(l.invert());this._nodes.forEach(d=>{var f;const h=d.getParent().getAbsoluteTransform(),p=d.getTransform().copy();p.translate(d.offsetX(),d.offsetY());const m=new Qe.Transform;m.multiply(h.copy().invert()).multiply(c).multiply(h).multiply(p);const S=m.decompose();d.setAttrs(S),this._fire("transform",{evt:n,target:d}),d._fire("transform",{evt:n,target:d}),(f=d.getLayer())===null||f===void 0||f.batchDraw()}),this.rotation(Qe.Util._getRotation(t.rotation)),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(t,n){this.findOne(t).setAttrs(n)}update(){var t,n=this._getNodeRect();this.rotation(Qe.Util._getRotation(n.rotation));var r=n.width,i=n.height,o=this.enabledAnchors(),s=this.resizeEnabled(),a=this.padding(),l=this.anchorSize();const u=this.find("._anchor");u.forEach(d=>{d.setAttrs({width:l,height:l,offsetX:l/2,offsetY:l/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:l/2+a,offsetY:l/2+a,visible:s&&o.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:r/2,y:0,offsetY:l/2+a,visible:s&&o.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:r,y:0,offsetX:l/2-a,offsetY:l/2+a,visible:s&&o.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:i/2,offsetX:l/2+a,visible:s&&o.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:r,y:i/2,offsetX:l/2-a,visible:s&&o.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:i,offsetX:l/2+a,offsetY:l/2-a,visible:s&&o.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:r/2,y:i,offsetY:l/2-a,visible:s&&o.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:r,y:i,offsetX:l/2-a,offsetY:l/2-a,visible:s&&o.indexOf("bottom-right")>=0}),this._batchChangeChild(".rotater",{x:r/2,y:-this.rotateAnchorOffset()*Qe.Util._sign(i)-a,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:r,height:i,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),x:0,y:0});const c=this.anchorStyleFunc();c&&u.forEach(d=>{c(d)}),(t=this.getLayer())===null||t===void 0||t.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();var t=this.findOne("."+this._movingAnchorName);t&&t.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),p6.Group.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return h6.Node.prototype.toObject.call(this)}clone(t){var n=h6.Node.prototype.clone.call(this,t);return n}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}}Cv.Transformer=ze;function Afe(e){return e instanceof Array||Qe.Util.warn("enabledAnchors value should be an array"),e instanceof Array&&e.forEach(function(t){Qm.indexOf(t)===-1&&Qe.Util.warn("Unknown anchor name: "+t+". Available names are: "+Qm.join(", "))}),e||[]}ze.prototype.className="Transformer";(0,bfe._registerNode)(ze);Ye.Factory.addGetterSetter(ze,"enabledAnchors",Qm,Afe);Ye.Factory.addGetterSetter(ze,"flipEnabled",!0,(0,la.getBooleanValidator)());Ye.Factory.addGetterSetter(ze,"resizeEnabled",!0);Ye.Factory.addGetterSetter(ze,"anchorSize",10,(0,la.getNumberValidator)());Ye.Factory.addGetterSetter(ze,"rotateEnabled",!0);Ye.Factory.addGetterSetter(ze,"rotationSnaps",[]);Ye.Factory.addGetterSetter(ze,"rotateAnchorOffset",50,(0,la.getNumberValidator)());Ye.Factory.addGetterSetter(ze,"rotationSnapTolerance",5,(0,la.getNumberValidator)());Ye.Factory.addGetterSetter(ze,"borderEnabled",!0);Ye.Factory.addGetterSetter(ze,"anchorStroke","rgb(0, 161, 255)");Ye.Factory.addGetterSetter(ze,"anchorStrokeWidth",1,(0,la.getNumberValidator)());Ye.Factory.addGetterSetter(ze,"anchorFill","white");Ye.Factory.addGetterSetter(ze,"anchorCornerRadius",0,(0,la.getNumberValidator)());Ye.Factory.addGetterSetter(ze,"borderStroke","rgb(0, 161, 255)");Ye.Factory.addGetterSetter(ze,"borderStrokeWidth",1,(0,la.getNumberValidator)());Ye.Factory.addGetterSetter(ze,"borderDash");Ye.Factory.addGetterSetter(ze,"keepRatio",!0);Ye.Factory.addGetterSetter(ze,"shiftBehavior","default");Ye.Factory.addGetterSetter(ze,"centeredScaling",!1);Ye.Factory.addGetterSetter(ze,"ignoreStroke",!1);Ye.Factory.addGetterSetter(ze,"padding",0,(0,la.getNumberValidator)());Ye.Factory.addGetterSetter(ze,"node");Ye.Factory.addGetterSetter(ze,"nodes");Ye.Factory.addGetterSetter(ze,"boundBoxFunc");Ye.Factory.addGetterSetter(ze,"anchorDragBoundFunc");Ye.Factory.addGetterSetter(ze,"anchorStyleFunc");Ye.Factory.addGetterSetter(ze,"shouldOverdrawWholeArea",!1);Ye.Factory.addGetterSetter(ze,"useSingleNodeRotation",!0);Ye.Factory.backCompat(ze,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});var Tv={};Object.defineProperty(Tv,"__esModule",{value:!0});Tv.Wedge=void 0;const Ev=Te,kfe=sn,Ofe=Pe,LN=de,Rfe=Pe;class Qo extends kfe.Shape{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,Ofe.Konva.getAngle(this.angle()),this.clockwise()),t.lineTo(0,0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}Tv.Wedge=Qo;Qo.prototype.className="Wedge";Qo.prototype._centroid=!0;Qo.prototype._attrsAffectingSize=["radius"];(0,Rfe._registerNode)(Qo);Ev.Factory.addGetterSetter(Qo,"radius",0,(0,LN.getNumberValidator)());Ev.Factory.addGetterSetter(Qo,"angle",0,(0,LN.getNumberValidator)());Ev.Factory.addGetterSetter(Qo,"clockwise",!1);Ev.Factory.backCompat(Qo,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});var Pv={};Object.defineProperty(Pv,"__esModule",{value:!0});Pv.Blur=void 0;const y6=Te,Ife=wt,Mfe=de;function v6(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}var Nfe=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],Dfe=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function Lfe(e,t){var n=e.data,r=e.width,i=e.height,o,s,a,l,u,c,d,f,h,p,m,S,v,y,g,b,_,w,x,T,P,E,A,$,M=t+t+1,C=r-1,O=i-1,I=t+1,N=I*(I+1)/2,R=new v6,D=null,L=R,j=null,U=null,G=Nfe[t],W=Dfe[t];for(a=1;a>W,A!==0?(A=255/A,n[c]=(f*G>>W)*A,n[c+1]=(h*G>>W)*A,n[c+2]=(p*G>>W)*A):n[c]=n[c+1]=n[c+2]=0,f-=S,h-=v,p-=y,m-=g,S-=j.r,v-=j.g,y-=j.b,g-=j.a,l=d+((l=o+t+1)>W,A>0?(A=255/A,n[l]=(f*G>>W)*A,n[l+1]=(h*G>>W)*A,n[l+2]=(p*G>>W)*A):n[l]=n[l+1]=n[l+2]=0,f-=S,h-=v,p-=y,m-=g,S-=j.r,v-=j.g,y-=j.b,g-=j.a,l=o+((l=s+I)0&&Lfe(t,n)};Pv.Blur=$fe;y6.Factory.addGetterSetter(Ife.Node,"blurRadius",0,(0,Mfe.getNumberValidator)(),y6.Factory.afterSetFilter);var Av={};Object.defineProperty(Av,"__esModule",{value:!0});Av.Brighten=void 0;const b6=Te,Ffe=wt,Bfe=de,jfe=function(e){var t=this.brightness()*255,n=e.data,r=n.length,i;for(i=0;i255?255:i,o=o<0?0:o>255?255:o,s=s<0?0:s>255?255:s,n[a]=i,n[a+1]=o,n[a+2]=s};kv.Contrast=Ufe;S6.Factory.addGetterSetter(Vfe.Node,"contrast",0,(0,zfe.getNumberValidator)(),S6.Factory.afterSetFilter);var Ov={};Object.defineProperty(Ov,"__esModule",{value:!0});Ov.Emboss=void 0;const Ws=Te,Rv=wt,Gfe=Rt,$N=de,Hfe=function(e){var t=this.embossStrength()*10,n=this.embossWhiteLevel()*255,r=this.embossDirection(),i=this.embossBlend(),o=0,s=0,a=e.data,l=e.width,u=e.height,c=l*4,d=u;switch(r){case"top-left":o=-1,s=-1;break;case"top":o=-1,s=0;break;case"top-right":o=-1,s=1;break;case"right":o=0,s=1;break;case"bottom-right":o=1,s=1;break;case"bottom":o=1,s=0;break;case"bottom-left":o=1,s=-1;break;case"left":o=0,s=-1;break;default:Gfe.Util.error("Unknown emboss direction: "+r)}do{var f=(d-1)*c,h=o;d+h<1&&(h=0),d+h>u&&(h=0);var p=(d-1+h)*l*4,m=l;do{var S=f+(m-1)*4,v=s;m+v<1&&(v=0),m+v>l&&(v=0);var y=p+(m-1+v)*4,g=a[S]-a[y],b=a[S+1]-a[y+1],_=a[S+2]-a[y+2],w=g,x=w>0?w:-w,T=b>0?b:-b,P=_>0?_:-_;if(T>x&&(w=b),P>x&&(w=_),w*=t,i){var E=a[S]+w,A=a[S+1]+w,$=a[S+2]+w;a[S]=E>255?255:E<0?0:E,a[S+1]=A>255?255:A<0?0:A,a[S+2]=$>255?255:$<0?0:$}else{var M=n-w;M<0?M=0:M>255&&(M=255),a[S]=a[S+1]=a[S+2]=M}}while(--m)}while(--d)};Ov.Emboss=Hfe;Ws.Factory.addGetterSetter(Rv.Node,"embossStrength",.5,(0,$N.getNumberValidator)(),Ws.Factory.afterSetFilter);Ws.Factory.addGetterSetter(Rv.Node,"embossWhiteLevel",.5,(0,$N.getNumberValidator)(),Ws.Factory.afterSetFilter);Ws.Factory.addGetterSetter(Rv.Node,"embossDirection","top-left",null,Ws.Factory.afterSetFilter);Ws.Factory.addGetterSetter(Rv.Node,"embossBlend",!1,null,Ws.Factory.afterSetFilter);var Iv={};Object.defineProperty(Iv,"__esModule",{value:!0});Iv.Enhance=void 0;const _6=Te,qfe=wt,Wfe=de;function Zb(e,t,n,r,i){var o=n-t,s=i-r,a;return o===0?r+s/2:s===0?r:(a=(e-t)/o,a=s*a+r,a)}const Kfe=function(e){var t=e.data,n=t.length,r=t[0],i=r,o,s=t[1],a=s,l,u=t[2],c=u,d,f,h=this.enhance();if(h!==0){for(f=0;fi&&(i=o),l=t[f+1],la&&(a=l),d=t[f+2],dc&&(c=d);i===r&&(i=255,r=0),a===s&&(a=255,s=0),c===u&&(c=255,u=0);var p,m,S,v,y,g,b,_,w;for(h>0?(m=i+h*(255-i),S=r-h*(r-0),y=a+h*(255-a),g=s-h*(s-0),_=c+h*(255-c),w=u-h*(u-0)):(p=(i+r)*.5,m=i+h*(i-p),S=r+h*(r-p),v=(a+s)*.5,y=a+h*(a-v),g=s+h*(s-v),b=(c+u)*.5,_=c+h*(c-b),w=u+h*(u-b)),f=0;fv?S:v;var y=s,g=o,b,_,w=360/g*Math.PI/180,x,T;for(_=0;_g?y:g;var b=s,_=o,w,x,T=n.polarRotation||0,P,E;for(c=0;ct&&(b=g,_=0,w=-1),i=0;i=0&&h=0&&p=0&&h=0&&p=255*4?255:0}return s}function uhe(e,t,n){for(var r=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],i=Math.round(Math.sqrt(r.length)),o=Math.floor(i/2),s=[],a=0;a=0&&h=0&&p=n))for(o=m;o=r||(s=(n*o+i)*4,a+=b[s+0],l+=b[s+1],u+=b[s+2],c+=b[s+3],g+=1);for(a=a/g,l=l/g,u=u/g,c=c/g,i=h;i=n))for(o=m;o=r||(s=(n*o+i)*4,b[s+0]=a,b[s+1]=l,b[s+2]=u,b[s+3]=c)}};jv.Pixelate=yhe;T6.Factory.addGetterSetter(ghe.Node,"pixelSize",8,(0,mhe.getNumberValidator)(),T6.Factory.afterSetFilter);var Vv={};Object.defineProperty(Vv,"__esModule",{value:!0});Vv.Posterize=void 0;const E6=Te,vhe=wt,bhe=de,She=function(e){var t=Math.round(this.levels()*254)+1,n=e.data,r=n.length,i=255/t,o;for(o=0;o255?255:e<0?0:Math.round(e)});Jm.Factory.addGetterSetter(NC.Node,"green",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)});Jm.Factory.addGetterSetter(NC.Node,"blue",0,_he.RGBComponent,Jm.Factory.afterSetFilter);var Uv={};Object.defineProperty(Uv,"__esModule",{value:!0});Uv.RGBA=void 0;const Bf=Te,Gv=wt,xhe=de,Che=function(e){var t=e.data,n=t.length,r=this.red(),i=this.green(),o=this.blue(),s=this.alpha(),a,l;for(a=0;a255?255:e<0?0:Math.round(e)});Bf.Factory.addGetterSetter(Gv.Node,"green",0,function(e){return this._filterUpToDate=!1,e>255?255:e<0?0:Math.round(e)});Bf.Factory.addGetterSetter(Gv.Node,"blue",0,xhe.RGBComponent,Bf.Factory.afterSetFilter);Bf.Factory.addGetterSetter(Gv.Node,"alpha",1,function(e){return this._filterUpToDate=!1,e>1?1:e<0?0:e});var Hv={};Object.defineProperty(Hv,"__esModule",{value:!0});Hv.Sepia=void 0;const The=function(e){var t=e.data,n=t.length,r,i,o,s;for(r=0;r127&&(u=255-u),c>127&&(c=255-c),d>127&&(d=255-d),t[l]=u,t[l+1]=c,t[l+2]=d}while(--a)}while(--o)};qv.Solarize=Ehe;var Wv={};Object.defineProperty(Wv,"__esModule",{value:!0});Wv.Threshold=void 0;const P6=Te,Phe=wt,Ahe=de,khe=function(e){var t=this.threshold()*255,n=e.data,r=n.length,i;for(i=0;i{const{width:r,height:i}=t,o=document.createElement("div"),s=new nd.Stage({container:o,width:r,height:i}),a=new nd.Layer,l=new nd.Layer;return a.add(new nd.Rect({...t,fill:n?"black":"white"})),e.forEach(u=>l.add(new nd.Line({points:u.points,stroke:n?"white":"black",strokeWidth:u.strokeWidth*2,tension:0,lineCap:"round",lineJoin:"round",shadowForStrokeEnabled:!1,globalCompositeOperation:u.tool==="brush"?"source-over":"destination-out"}))),s.add(a),s.add(l),o.remove(),s},gpe=async(e,t,n)=>new Promise((r,i)=>{const o=document.createElement("canvas");o.width=t,o.height=n;const s=o.getContext("2d"),a=new Image;if(!s){o.remove(),i("Unable to get context");return}a.onload=function(){s.drawImage(a,0,0),o.remove(),r(s.getImageData(0,0,t,n))},a.src=e}),O6=async(e,t)=>{const n=e.toDataURL(t);return await gpe(n,t.width,t.height)},mpe=async(e,t,n,r,i)=>{const o=fe("canvas"),s=tv(),a=Ple();if(!s||!a){o.error("Unable to find canvas / stage");return}const l={...t,...n},u=s.clone();u.scale({x:1,y:1});const c=u.getAbsolutePosition(),d={x:l.x+c.x,y:l.y+c.y,width:l.width,height:l.height},f=await Km(u,d),h=await O6(u,d),p=await ppe(r?e.objects.filter(MR):[],l,i),m=await Km(p,l),S=await O6(p,l);return{baseBlob:f,baseImageData:h,maskBlob:m,maskImageData:S}},ype=e=>{let t=!0,n=!1;const r=e.length;let i=3;for(i;i{const t=e.length;let n=0;for(n;n{const{isPartiallyTransparent:n,isFullyTransparent:r}=ype(e.data),i=vpe(t.data);return n?r?"txt2img":"outpaint":i?"inpaint":"img2img"},Spe=e=>oR(e,n=>n.isEnabled&&(!!n.processedControlImage||n.processorType==="none"&&!!n.controlImage)),Kv=(e,t,n)=>{const{isEnabled:r,controlNets:i}=e.controlNet,o=Spe(i),s=t.nodes[lt];if(r&&o.length&&o.length){const a={id:Rp,type:"collect",is_intermediate:!0};t.nodes[Rp]=a,t.edges.push({source:{node_id:Rp,field:"collection"},destination:{node_id:n,field:"control"}}),o.forEach(l=>{const{controlNetId:u,controlImage:c,processedControlImage:d,beginStepPct:f,endStepPct:h,controlMode:p,resizeMode:m,model:S,processorType:v,weight:y}=l,g={id:`control_net_${u}`,type:"controlnet",is_intermediate:!0,begin_step_percent:f,end_step_percent:h,control_mode:p,resize_mode:m,control_model:S,control_weight:y};if(d&&v!=="none")g.image={image_name:d};else if(c)g.image={image_name:c};else return;if(t.nodes[g.id]=g,s){const b=_0(g,["id","type"]);s.controlnets.push(b)}t.edges.push({source:{node_id:g.id,field:"control"},destination:{node_id:Rp,field:"item"}})})}},xc=(e,t)=>{const{positivePrompt:n,iterations:r,seed:i,shouldRandomizeSeed:o}=e.generation,{combinatorial:s,isEnabled:a,maxPrompts:l}=e.dynamicPrompts,u=t.nodes[lt];if(a){rY(t.nodes[Fe],"prompt");const c={id:zb,type:"dynamic_prompt",is_intermediate:!0,max_prompts:s?l:r,combinatorial:s,prompt:n},d={id:lr,type:"iterate",is_intermediate:!0};if(t.nodes[zb]=c,t.nodes[lr]=d,t.edges.push({source:{node_id:zb,field:"prompt_collection"},destination:{node_id:lr,field:"collection"}},{source:{node_id:lr,field:"item"},destination:{node_id:Fe,field:"prompt"}}),u&&t.edges.push({source:{node_id:lr,field:"item"},destination:{node_id:lt,field:"positive_prompt"}}),o){const f={id:Fi,type:"rand_int",is_intermediate:!0};t.nodes[Fi]=f,t.edges.push({source:{node_id:Fi,field:"a"},destination:{node_id:Le,field:"seed"}}),u&&t.edges.push({source:{node_id:Fi,field:"a"},destination:{node_id:lt,field:"seed"}})}else t.nodes[Le].seed=i,u&&(u.seed=i)}else{u&&(u.positive_prompt=n);const c={id:Co,type:"range_of_size",is_intermediate:!0,size:r,step:1},d={id:lr,type:"iterate",is_intermediate:!0};if(t.nodes[lr]=d,t.nodes[Co]=c,t.edges.push({source:{node_id:Co,field:"collection"},destination:{node_id:lr,field:"collection"}}),t.edges.push({source:{node_id:lr,field:"item"},destination:{node_id:Le,field:"seed"}}),u&&t.edges.push({source:{node_id:lr,field:"item"},destination:{node_id:lt,field:"seed"}}),o){const f={id:Fi,type:"rand_int",is_intermediate:!0};t.nodes[Fi]=f,t.edges.push({source:{node_id:Fi,field:"a"},destination:{node_id:Co,field:"start"}})}else c.start=i}},Mh=(e,t,n)=>{const{loras:r}=e.lora,i=hR(r),o=t.nodes[lt];i>0&&(t.edges=t.edges.filter(l=>!(l.source.node_id===pt&&["unet"].includes(l.source.field))),t.edges=t.edges.filter(l=>!(l.source.node_id===rt&&["clip"].includes(l.source.field))));let s="",a=0;Qa(r,l=>{const{model_name:u,base_model:c,weight:d}=l,f=`${uce}_${u.replace(".","_")}`,h={type:"lora_loader",id:f,is_intermediate:!0,lora:{model_name:u,base_model:c},weight:d};o&&o.loras.push({lora:{model_name:u,base_model:c},weight:d}),t.nodes[f]=h,a===0?(t.edges.push({source:{node_id:pt,field:"unet"},destination:{node_id:f,field:"unet"}}),t.edges.push({source:{node_id:rt,field:"clip"},destination:{node_id:f,field:"clip"}})):(t.edges.push({source:{node_id:s,field:"unet"},destination:{node_id:f,field:"unet"}}),t.edges.push({source:{node_id:s,field:"clip"},destination:{node_id:f,field:"clip"}})),a===i-1&&(t.edges.push({source:{node_id:f,field:"unet"},destination:{node_id:n,field:"unet"}}),t.edges.push({source:{node_id:f,field:"clip"},destination:{node_id:Fe,field:"clip"}}),t.edges.push({source:{node_id:f,field:"clip"},destination:{node_id:qe,field:"clip"}})),s=f,a+=1})},jN=Jn(e=>e.ui,e=>AR[e.activeTab],{memoizeOptions:{equalityCheck:S0}}),r4e=Jn(e=>e.ui,e=>e.activeTab,{memoizeOptions:{equalityCheck:S0}}),i4e=Jn(e=>e.ui,e=>e,{memoizeOptions:{equalityCheck:S0}}),xl=(e,t,n=nt)=>{const i=jN(e)==="unifiedCanvas"?!e.canvas.shouldAutoSave:!1,o=t.nodes[n],s=t.nodes[lt];if(!o)return;o.is_intermediate=!0;const a={id:fu,type:"img_nsfw",is_intermediate:i};t.nodes[fu]=a,t.edges.push({source:{node_id:n,field:"image"},destination:{node_id:fu,field:"image"}}),s&&t.edges.push({source:{node_id:lt,field:"metadata"},destination:{node_id:fu,field:"metadata"}})},Nh=(e,t)=>{const{vae:n}=e.generation,r=!n,i=t.nodes[lt];r||(t.nodes[Zc]={type:"vae_loader",id:Zc,is_intermediate:!0,vae_model:n}),(t.id===bC||t.id===Xm)&&t.edges.push({source:{node_id:r?pt:Zc,field:"vae"},destination:{node_id:nt,field:"vae"}}),t.id===Xm&&t.edges.push({source:{node_id:r?pt:Zc,field:"vae"},destination:{node_id:bt,field:"vae"}}),t.id===iN&&t.edges.push({source:{node_id:r?pt:Zc,field:"vae"},destination:{node_id:Mi,field:"vae"}}),n&&i&&(i.vae=n)},Cl=(e,t,n=nt)=>{const i=jN(e)==="unifiedCanvas"?!e.canvas.shouldAutoSave:!1,o=t.nodes[n],s=t.nodes[fu],a=t.nodes[lt];if(!o)return;const l={id:Qc,type:"img_watermark",is_intermediate:i};t.nodes[Qc]=l,o.is_intermediate=!0,s?(s.is_intermediate=!0,t.edges.push({source:{node_id:fu,field:"image"},destination:{node_id:Qc,field:"image"}})):t.edges.push({source:{node_id:n,field:"image"},destination:{node_id:Qc,field:"image"}}),a&&t.edges.push({source:{node_id:lt,field:"metadata"},destination:{node_id:Qc,field:"metadata"}})},_pe=(e,t)=>{const n=fe("nodes"),{positivePrompt:r,negativePrompt:i,model:o,cfgScale:s,scheduler:a,steps:l,img2imgStrength:u,clipSkip:c,shouldUseCpuNoise:d,shouldUseNoiseSettings:f}=e.generation,{width:h,height:p}=e.canvas.boundingBoxDimensions,{shouldAutoSave:m}=e.canvas;if(!o)throw n.error("No model found in state"),new Error("No model found in state");const S=f?d:Wo.shouldUseCpuNoise,v={id:Xm,nodes:{[Fe]:{type:"compel",id:Fe,is_intermediate:!0,prompt:r},[qe]:{type:"compel",id:qe,is_intermediate:!0,prompt:i},[Le]:{type:"noise",id:Le,is_intermediate:!0,use_cpu:S},[pt]:{type:"main_model_loader",id:pt,is_intermediate:!0,model:o},[rt]:{type:"clip_skip",id:rt,is_intermediate:!0,skipped_layers:c},[Kt]:{type:"l2l",id:Kt,is_intermediate:!0,cfg_scale:s,scheduler:a,steps:l,strength:u},[bt]:{type:"i2l",id:bt,is_intermediate:!0},[nt]:{type:"l2i",id:nt,is_intermediate:!m}},edges:[{source:{node_id:pt,field:"clip"},destination:{node_id:rt,field:"clip"}},{source:{node_id:rt,field:"clip"},destination:{node_id:Fe,field:"clip"}},{source:{node_id:rt,field:"clip"},destination:{node_id:qe,field:"clip"}},{source:{node_id:Kt,field:"latents"},destination:{node_id:nt,field:"latents"}},{source:{node_id:bt,field:"latents"},destination:{node_id:Kt,field:"latents"}},{source:{node_id:Le,field:"noise"},destination:{node_id:Kt,field:"noise"}},{source:{node_id:pt,field:"unet"},destination:{node_id:Kt,field:"unet"}},{source:{node_id:qe,field:"conditioning"},destination:{node_id:Kt,field:"negative_conditioning"}},{source:{node_id:Fe,field:"conditioning"},destination:{node_id:Kt,field:"positive_conditioning"}}]};if(t.width!==h||t.height!==p){const y={id:Qn,type:"img_resize",image:{image_name:t.image_name},is_intermediate:!0,width:h,height:p};v.nodes[Qn]=y,v.edges.push({source:{node_id:Qn,field:"image"},destination:{node_id:bt,field:"image"}}),v.edges.push({source:{node_id:Qn,field:"width"},destination:{node_id:Le,field:"width"}}),v.edges.push({source:{node_id:Qn,field:"height"},destination:{node_id:Le,field:"height"}})}else v.nodes[bt].image={image_name:t.image_name},v.edges.push({source:{node_id:bt,field:"width"},destination:{node_id:Le,field:"width"}}),v.edges.push({source:{node_id:bt,field:"height"},destination:{node_id:Le,field:"height"}});return v.nodes[lt]={id:lt,type:"metadata_accumulator",generation_mode:"img2img",cfg_scale:s,height:p,width:h,positive_prompt:"",negative_prompt:i,model:o,seed:0,steps:l,rand_device:S?"cpu":"cuda",scheduler:a,vae:void 0,controlnets:[],loras:[],clip_skip:c,strength:u,init_image:t.image_name},Mh(e,v,Kt),Nh(e,v),xc(e,v),Kv(e,v,Kt),e.system.shouldUseNSFWChecker&&xl(e,v),e.system.shouldUseWatermarker&&Cl(e,v),v},wpe=(e,t,n)=>{const r=fe("nodes"),{positivePrompt:i,negativePrompt:o,model:s,cfgScale:a,scheduler:l,steps:u,img2imgStrength:c,shouldFitToWidthHeight:d,iterations:f,seed:h,shouldRandomizeSeed:p,seamSize:m,seamBlur:S,seamSteps:v,seamStrength:y,tileSize:g,infillMethod:b,clipSkip:_}=e.generation;if(!s)throw r.error("No model found in state"),new Error("No model found in state");const{width:w,height:x}=e.canvas.boundingBoxDimensions,{scaledBoundingBoxDimensions:T,boundingBoxScaleMethod:P,shouldAutoSave:E}=e.canvas,A={id:iN,nodes:{[Mi]:{is_intermediate:!E,type:"inpaint",id:Mi,steps:u,width:w,height:x,cfg_scale:a,scheduler:l,image:{image_name:t.image_name},strength:c,fit:d,mask:{image_name:n.image_name},seam_size:m,seam_blur:S,seam_strength:y,seam_steps:v,tile_size:b==="tile"?g:void 0,infill_method:b,inpaint_width:P!=="none"?T.width:void 0,inpaint_height:P!=="none"?T.height:void 0},[Fe]:{type:"compel",id:Fe,is_intermediate:!0,prompt:i},[qe]:{type:"compel",id:qe,is_intermediate:!0,prompt:o},[pt]:{type:"main_model_loader",id:pt,is_intermediate:!0,model:s},[rt]:{type:"clip_skip",id:rt,is_intermediate:!0,skipped_layers:_},[Co]:{type:"range_of_size",id:Co,is_intermediate:!0,size:f,step:1},[lr]:{type:"iterate",id:lr,is_intermediate:!0}},edges:[{source:{node_id:pt,field:"unet"},destination:{node_id:Mi,field:"unet"}},{source:{node_id:pt,field:"clip"},destination:{node_id:rt,field:"clip"}},{source:{node_id:rt,field:"clip"},destination:{node_id:Fe,field:"clip"}},{source:{node_id:rt,field:"clip"},destination:{node_id:qe,field:"clip"}},{source:{node_id:qe,field:"conditioning"},destination:{node_id:Mi,field:"negative_conditioning"}},{source:{node_id:Fe,field:"conditioning"},destination:{node_id:Mi,field:"positive_conditioning"}},{source:{node_id:Co,field:"collection"},destination:{node_id:lr,field:"collection"}},{source:{node_id:lr,field:"item"},destination:{node_id:Mi,field:"seed"}}]};if(Mh(e,A,Mi),Nh(e,A),p){const $={id:Fi,type:"rand_int"};A.nodes[Fi]=$,A.edges.push({source:{node_id:Fi,field:"a"},destination:{node_id:Co,field:"start"}})}else A.nodes[Co].start=h;return e.system.shouldUseNSFWChecker&&xl(e,A,Mi),e.system.shouldUseWatermarker&&Cl(e,A,Mi),A},xpe=e=>{const t=fe("nodes"),{positivePrompt:n,negativePrompt:r,model:i,cfgScale:o,scheduler:s,steps:a,clipSkip:l,shouldUseCpuNoise:u,shouldUseNoiseSettings:c}=e.generation,{width:d,height:f}=e.canvas.boundingBoxDimensions,{shouldAutoSave:h}=e.canvas;if(!i)throw t.error("No model found in state"),new Error("No model found in state");const p=c?u:Wo.shouldUseCpuNoise,m={id:bC,nodes:{[Fe]:{type:"compel",id:Fe,is_intermediate:!0,prompt:n},[qe]:{type:"compel",id:qe,is_intermediate:!0,prompt:r},[Le]:{type:"noise",id:Le,is_intermediate:!0,width:d,height:f,use_cpu:p},[dn]:{type:"t2l",id:dn,is_intermediate:!0,cfg_scale:o,scheduler:s,steps:a},[pt]:{type:"main_model_loader",id:pt,is_intermediate:!0,model:i},[rt]:{type:"clip_skip",id:rt,is_intermediate:!0,skipped_layers:l},[nt]:{type:"l2i",id:nt,is_intermediate:!h}},edges:[{source:{node_id:qe,field:"conditioning"},destination:{node_id:dn,field:"negative_conditioning"}},{source:{node_id:Fe,field:"conditioning"},destination:{node_id:dn,field:"positive_conditioning"}},{source:{node_id:pt,field:"clip"},destination:{node_id:rt,field:"clip"}},{source:{node_id:rt,field:"clip"},destination:{node_id:Fe,field:"clip"}},{source:{node_id:rt,field:"clip"},destination:{node_id:qe,field:"clip"}},{source:{node_id:pt,field:"unet"},destination:{node_id:dn,field:"unet"}},{source:{node_id:dn,field:"latents"},destination:{node_id:nt,field:"latents"}},{source:{node_id:Le,field:"noise"},destination:{node_id:dn,field:"noise"}}]};return m.nodes[lt]={id:lt,type:"metadata_accumulator",generation_mode:"txt2img",cfg_scale:o,height:f,width:d,positive_prompt:"",negative_prompt:r,model:i,seed:0,steps:a,rand_device:p?"cpu":"cuda",scheduler:s,vae:void 0,controlnets:[],loras:[],clip_skip:l},Mh(e,m,dn),Nh(e,m),xc(e,m),Kv(e,m,dn),e.system.shouldUseNSFWChecker&&xl(e,m),e.system.shouldUseWatermarker&&Cl(e,m),m},Cpe=(e,t,n,r)=>{let i;if(t==="txt2img")i=xpe(e);else if(t==="img2img"){if(!n)throw new Error("Missing canvas init image");i=_pe(e,n)}else{if(!n||!r)throw new Error("Missing canvas init and mask images");i=wpe(e,n,r)}return i},Tpe=()=>{le({predicate:e=>Ph.match(e)&&e.payload==="unifiedCanvas",effect:async(e,{getState:t,dispatch:n,take:r})=>{const i=fe("session"),o=t(),{layerState:s,boundingBoxCoordinates:a,boundingBoxDimensions:l,isMaskEnabled:u,shouldPreserveMaskedArea:c}=o.canvas,d=await mpe(s,a,l,u,c);if(!d){i.error("Unable to create canvas data");return}const{baseBlob:f,baseImageData:h,maskBlob:p,maskImageData:m}=d,S=bpe(h,m);if(o.system.enableImageDebugging){const x=await XE(f),T=await XE(p);gce([{base64:T,caption:"mask b64"},{base64:x,caption:"image b64"}])}i.debug(`Generation mode: ${S}`);let v,y;["img2img","inpaint","outpaint"].includes(S)&&(v=await n(he.endpoints.uploadImage.initiate({file:new File([f],"canvasInitImage.png",{type:"image/png"}),image_category:"general",is_intermediate:!0})).unwrap()),["inpaint","outpaint"].includes(S)&&(y=await n(he.endpoints.uploadImage.initiate({file:new File([p],"canvasMaskImage.png",{type:"image/png"}),image_category:"mask",is_intermediate:!0})).unwrap());const g=Cpe(o,S,v,y);i.debug({graph:ra(g)},"Canvas graph built"),n(KM(g));const{requestId:b}=n(On({graph:g})),[_]=await r(x=>On.fulfilled.match(x)&&x.meta.requestId===b),w=_.payload.id;["img2img","inpaint"].includes(S)&&v&&n(he.endpoints.changeImageSessionId.initiate({imageDTO:v,session_id:w})),["inpaint"].includes(S)&&y&&n(he.endpoints.changeImageSessionId.initiate({imageDTO:y,session_id:w})),o.canvas.layerState.stagingArea.boundingBox||n(jQ({sessionId:w,boundingBox:{...o.canvas.boundingBoxCoordinates,...o.canvas.boundingBoxDimensions}})),n(VQ(w)),n(pl())}})},Epe=e=>{const t=fe("nodes"),{positivePrompt:n,negativePrompt:r,model:i,cfgScale:o,scheduler:s,steps:a,initialImage:l,img2imgStrength:u,shouldFitToWidthHeight:c,width:d,height:f,clipSkip:h,shouldUseCpuNoise:p,shouldUseNoiseSettings:m,vaePrecision:S}=e.generation;if(!l)throw t.error("No initial image found in state"),new Error("No initial image found in state");if(!i)throw t.error("No model found in state"),new Error("No model found in state");const v=m?p:Wo.shouldUseCpuNoise,y={id:Xm,nodes:{[pt]:{type:"main_model_loader",id:pt,model:i},[rt]:{type:"clip_skip",id:rt,skipped_layers:h},[Fe]:{type:"compel",id:Fe,prompt:n},[qe]:{type:"compel",id:qe,prompt:r},[Le]:{type:"noise",id:Le,use_cpu:v},[nt]:{type:"l2i",id:nt,fp32:S==="fp32"},[Kt]:{type:"l2l",id:Kt,cfg_scale:o,scheduler:s,steps:a,strength:u},[bt]:{type:"i2l",id:bt,fp32:S==="fp32"}},edges:[{source:{node_id:pt,field:"unet"},destination:{node_id:Kt,field:"unet"}},{source:{node_id:pt,field:"clip"},destination:{node_id:rt,field:"clip"}},{source:{node_id:rt,field:"clip"},destination:{node_id:Fe,field:"clip"}},{source:{node_id:rt,field:"clip"},destination:{node_id:qe,field:"clip"}},{source:{node_id:Kt,field:"latents"},destination:{node_id:nt,field:"latents"}},{source:{node_id:bt,field:"latents"},destination:{node_id:Kt,field:"latents"}},{source:{node_id:Le,field:"noise"},destination:{node_id:Kt,field:"noise"}},{source:{node_id:qe,field:"conditioning"},destination:{node_id:Kt,field:"negative_conditioning"}},{source:{node_id:Fe,field:"conditioning"},destination:{node_id:Kt,field:"positive_conditioning"}}]};if(c&&(l.width!==d||l.height!==f)){const g={id:Qn,type:"img_resize",image:{image_name:l.imageName},is_intermediate:!0,width:d,height:f};y.nodes[Qn]=g,y.edges.push({source:{node_id:Qn,field:"image"},destination:{node_id:bt,field:"image"}}),y.edges.push({source:{node_id:Qn,field:"width"},destination:{node_id:Le,field:"width"}}),y.edges.push({source:{node_id:Qn,field:"height"},destination:{node_id:Le,field:"height"}})}else y.nodes[bt].image={image_name:l.imageName},y.edges.push({source:{node_id:bt,field:"width"},destination:{node_id:Le,field:"width"}}),y.edges.push({source:{node_id:bt,field:"height"},destination:{node_id:Le,field:"height"}});return y.nodes[lt]={id:lt,type:"metadata_accumulator",generation_mode:"img2img",cfg_scale:o,height:f,width:d,positive_prompt:"",negative_prompt:r,model:i,seed:0,steps:a,rand_device:v?"cpu":"cuda",scheduler:s,vae:void 0,controlnets:[],loras:[],clip_skip:h,strength:u,init_image:l.imageName},Mh(e,y,Kt),Nh(e,y),xc(e,y),Kv(e,y,Kt),e.system.shouldUseNSFWChecker&&xl(e,y),e.system.shouldUseWatermarker&&Cl(e,y),y},VN=(e,t,n)=>{const{positivePrompt:r,negativePrompt:i}=e.generation,{refinerModel:o,refinerAestheticScore:s,positiveStylePrompt:a,negativeStylePrompt:l,refinerSteps:u,refinerScheduler:c,refinerCFGScale:d,refinerStart:f}=e.sdxl;if(!o)return;const h=t.nodes[lt];h&&(h.refiner_model=o,h.refiner_aesthetic_store=s,h.refiner_cfg_scale=d,h.refiner_scheduler=c,h.refiner_start=f,h.refiner_steps=u),t.edges=t.edges.filter(p=>!(p.source.node_id===n&&["latents"].includes(p.source.field))),t.edges=t.edges.filter(p=>!(p.source.node_id===en&&["vae"].includes(p.source.field))),n===Ni&&t.edges.push({source:{node_id:en,field:"vae"},destination:{node_id:bt,field:"vae"}}),t.nodes[zl]={type:"sdxl_refiner_model_loader",id:zl,model:o},t.nodes[Ip]={type:"sdxl_refiner_compel_prompt",id:Ip,style:`${r} ${a}`,aesthetic_score:s},t.nodes[Mp]={type:"sdxl_refiner_compel_prompt",id:Mp,style:`${i} ${l}`,aesthetic_score:s},t.nodes[ma]={type:"l2l_sdxl",id:ma,cfg_scale:d,steps:u/(1-Math.min(f,.99)),scheduler:c,denoising_start:f,denoising_end:1},t.edges.push({source:{node_id:zl,field:"unet"},destination:{node_id:ma,field:"unet"}},{source:{node_id:zl,field:"vae"},destination:{node_id:nt,field:"vae"}},{source:{node_id:zl,field:"clip2"},destination:{node_id:Ip,field:"clip2"}},{source:{node_id:zl,field:"clip2"},destination:{node_id:Mp,field:"clip2"}},{source:{node_id:Ip,field:"conditioning"},destination:{node_id:ma,field:"positive_conditioning"}},{source:{node_id:Mp,field:"conditioning"},destination:{node_id:ma,field:"negative_conditioning"}},{source:{node_id:n,field:"latents"},destination:{node_id:ma,field:"latents"}},{source:{node_id:ma,field:"latents"},destination:{node_id:nt,field:"latents"}})},Ppe=e=>{const t=fe("nodes"),{positivePrompt:n,negativePrompt:r,model:i,cfgScale:o,scheduler:s,steps:a,initialImage:l,shouldFitToWidthHeight:u,width:c,height:d,clipSkip:f,shouldUseCpuNoise:h,shouldUseNoiseSettings:p,vaePrecision:m}=e.generation,{positiveStylePrompt:S,negativeStylePrompt:v,shouldConcatSDXLStylePrompt:y,shouldUseSDXLRefiner:g,refinerStart:b,sdxlImg2ImgDenoisingStrength:_}=e.sdxl;if(!l)throw t.error("No initial image found in state"),new Error("No initial image found in state");if(!i)throw t.error("No model found in state"),new Error("No model found in state");const w=p?h:Wo.shouldUseCpuNoise,x={id:dce,nodes:{[en]:{type:"sdxl_model_loader",id:en,model:i},[Fe]:{type:"sdxl_compel_prompt",id:Fe,prompt:n,style:y?`${n} ${S}`:S},[qe]:{type:"sdxl_compel_prompt",id:qe,prompt:r,style:y?`${r} ${v}`:v},[Le]:{type:"noise",id:Le,use_cpu:w},[nt]:{type:"l2i",id:nt,fp32:m==="fp32"},[Ni]:{type:"l2l_sdxl",id:Ni,cfg_scale:o,scheduler:s,steps:a,denoising_start:g?Math.min(b,1-_):1-_,denoising_end:g?b:1},[bt]:{type:"i2l",id:bt,fp32:m==="fp32"}},edges:[{source:{node_id:en,field:"unet"},destination:{node_id:Ni,field:"unet"}},{source:{node_id:en,field:"vae"},destination:{node_id:nt,field:"vae"}},{source:{node_id:en,field:"vae"},destination:{node_id:bt,field:"vae"}},{source:{node_id:en,field:"clip"},destination:{node_id:Fe,field:"clip"}},{source:{node_id:en,field:"clip2"},destination:{node_id:Fe,field:"clip2"}},{source:{node_id:en,field:"clip"},destination:{node_id:qe,field:"clip"}},{source:{node_id:en,field:"clip2"},destination:{node_id:qe,field:"clip2"}},{source:{node_id:Ni,field:"latents"},destination:{node_id:nt,field:"latents"}},{source:{node_id:bt,field:"latents"},destination:{node_id:Ni,field:"latents"}},{source:{node_id:Le,field:"noise"},destination:{node_id:Ni,field:"noise"}},{source:{node_id:Fe,field:"conditioning"},destination:{node_id:Ni,field:"positive_conditioning"}},{source:{node_id:qe,field:"conditioning"},destination:{node_id:Ni,field:"negative_conditioning"}}]};if(u&&(l.width!==c||l.height!==d)){const T={id:Qn,type:"img_resize",image:{image_name:l.imageName},is_intermediate:!0,width:c,height:d};x.nodes[Qn]=T,x.edges.push({source:{node_id:Qn,field:"image"},destination:{node_id:bt,field:"image"}}),x.edges.push({source:{node_id:Qn,field:"width"},destination:{node_id:Le,field:"width"}}),x.edges.push({source:{node_id:Qn,field:"height"},destination:{node_id:Le,field:"height"}})}else x.nodes[bt].image={image_name:l.imageName},x.edges.push({source:{node_id:bt,field:"width"},destination:{node_id:Le,field:"width"}}),x.edges.push({source:{node_id:bt,field:"height"},destination:{node_id:Le,field:"height"}});return x.nodes[lt]={id:lt,type:"metadata_accumulator",generation_mode:"sdxl_img2img",cfg_scale:o,height:d,width:c,positive_prompt:"",negative_prompt:r,model:i,seed:0,steps:a,rand_device:w?"cpu":"cuda",scheduler:s,vae:void 0,controlnets:[],loras:[],clip_skip:f,strength:_,init_image:l.imageName,positive_style_prompt:S,negative_style_prompt:v},x.edges.push({source:{node_id:lt,field:"metadata"},destination:{node_id:nt,field:"metadata"}}),g&&VN(e,x,Ni),xc(e,x),e.system.shouldUseNSFWChecker&&xl(e,x),e.system.shouldUseWatermarker&&Cl(e,x),x},Ape=()=>{le({predicate:e=>Ph.match(e)&&e.payload==="img2img",effect:async(e,{getState:t,dispatch:n,take:r})=>{const i=fe("session"),o=t(),s=o.generation.model;let a;s&&s.base_model==="sdxl"?a=Ppe(o):a=Epe(o),n(WM(a)),i.debug({graph:ra(a)},"Image to Image graph built"),n(On({graph:a})),await r(On.fulfilled.match),n(pl())}})};let jp;const kpe=new Uint8Array(16);function Ope(){if(!jp&&(jp=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!jp))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return jp(kpe)}const Cn=[];for(let e=0;e<256;++e)Cn.push((e+256).toString(16).slice(1));function Rpe(e,t=0){return(Cn[e[t+0]]+Cn[e[t+1]]+Cn[e[t+2]]+Cn[e[t+3]]+"-"+Cn[e[t+4]]+Cn[e[t+5]]+"-"+Cn[e[t+6]]+Cn[e[t+7]]+"-"+Cn[e[t+8]]+Cn[e[t+9]]+"-"+Cn[e[t+10]]+Cn[e[t+11]]+Cn[e[t+12]]+Cn[e[t+13]]+Cn[e[t+14]]+Cn[e[t+15]]).toLowerCase()}const Ipe=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),R6={randomUUID:Ipe};function Mpe(e,t,n){if(R6.randomUUID&&!t&&!e)return R6.randomUUID();e=e||{};const r=e.random||(e.rng||Ope)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){n=n||0;for(let i=0;i<16;++i)t[n+i]=r[i];return t}return Rpe(r)}const Npe=e=>{if(e.type==="color"&&e.value){const t=Ln(e.value),{r:n,g:r,b:i,a:o}=e.value,s=Math.max(0,Math.min(o*255,255));return Object.assign(t,{r:n,g:r,b:i,a:s}),t}return e.value},Dpe=e=>{const{nodes:t,edges:n}=e.nodes,i=t.filter(a=>a.type!=="progress_image").reduce((a,l)=>{const{id:u,data:c}=l,{type:d,inputs:f}=c,h=Lx(f,(m,S,v)=>{const y=Npe(S);return m[v]=y,m},{}),p={type:d,id:u,...h};return Object.assign(a,{[u]:p}),a},{}),o=n.reduce((a,l)=>{const{source:u,target:c,sourceHandle:d,targetHandle:f}=l;return a.push({source:{node_id:u,field:d},destination:{node_id:c,field:f}}),a},[]);return o.forEach(a=>{const l=i[a.destination.node_id],u=a.destination.field;i[a.destination.node_id]=_0(l,u)}),{id:Mpe(),nodes:i,edges:o}},Lpe=()=>{le({predicate:e=>Ph.match(e)&&e.payload==="nodes",effect:async(e,{getState:t,dispatch:n,take:r})=>{const i=fe("session"),o=t(),s=Dpe(o);n(XM(s)),i.debug({graph:ra(s)},"Nodes graph built"),n(On({graph:s})),await r(On.fulfilled.match),n(pl())}})},$pe=e=>{const t=fe("nodes"),{positivePrompt:n,negativePrompt:r,model:i,cfgScale:o,scheduler:s,steps:a,width:l,height:u,clipSkip:c,shouldUseCpuNoise:d,shouldUseNoiseSettings:f,vaePrecision:h}=e.generation,{positiveStylePrompt:p,negativeStylePrompt:m,shouldConcatSDXLStylePrompt:S,shouldUseSDXLRefiner:v,refinerStart:y}=e.sdxl,g=f?d:Wo.shouldUseCpuNoise;if(!i)throw t.error("No model found in state"),new Error("No model found in state");const b={id:cce,nodes:{[en]:{type:"sdxl_model_loader",id:en,model:i},[Fe]:{type:"sdxl_compel_prompt",id:Fe,prompt:n,style:S?`${n} ${p}`:p},[qe]:{type:"sdxl_compel_prompt",id:qe,prompt:r,style:S?`${r} ${m}`:m},[Le]:{type:"noise",id:Le,width:l,height:u,use_cpu:g},[is]:{type:"t2l_sdxl",id:is,cfg_scale:o,scheduler:s,steps:a,denoising_end:v?y:1},[nt]:{type:"l2i",id:nt,fp32:h==="fp32"}},edges:[{source:{node_id:en,field:"unet"},destination:{node_id:is,field:"unet"}},{source:{node_id:en,field:"vae"},destination:{node_id:nt,field:"vae"}},{source:{node_id:en,field:"clip"},destination:{node_id:Fe,field:"clip"}},{source:{node_id:en,field:"clip2"},destination:{node_id:Fe,field:"clip2"}},{source:{node_id:en,field:"clip"},destination:{node_id:qe,field:"clip"}},{source:{node_id:en,field:"clip2"},destination:{node_id:qe,field:"clip2"}},{source:{node_id:Fe,field:"conditioning"},destination:{node_id:is,field:"positive_conditioning"}},{source:{node_id:qe,field:"conditioning"},destination:{node_id:is,field:"negative_conditioning"}},{source:{node_id:Le,field:"noise"},destination:{node_id:is,field:"noise"}},{source:{node_id:is,field:"latents"},destination:{node_id:nt,field:"latents"}}]};return b.nodes[lt]={id:lt,type:"metadata_accumulator",generation_mode:"sdxl_txt2img",cfg_scale:o,height:u,width:l,positive_prompt:"",negative_prompt:r,model:i,seed:0,steps:a,rand_device:g?"cpu":"cuda",scheduler:s,vae:void 0,controlnets:[],loras:[],clip_skip:c,positive_style_prompt:p,negative_style_prompt:m},b.edges.push({source:{node_id:lt,field:"metadata"},destination:{node_id:nt,field:"metadata"}}),v&&VN(e,b,is),xc(e,b),e.system.shouldUseNSFWChecker&&xl(e,b),e.system.shouldUseWatermarker&&Cl(e,b),b},Fpe=e=>{const t=fe("nodes"),{positivePrompt:n,negativePrompt:r,model:i,cfgScale:o,scheduler:s,steps:a,width:l,height:u,clipSkip:c,shouldUseCpuNoise:d,shouldUseNoiseSettings:f,vaePrecision:h}=e.generation,p=f?d:Wo.shouldUseCpuNoise;if(!i)throw t.error("No model found in state"),new Error("No model found in state");const m={id:bC,nodes:{[pt]:{type:"main_model_loader",id:pt,model:i},[rt]:{type:"clip_skip",id:rt,skipped_layers:c},[Fe]:{type:"compel",id:Fe,prompt:n},[qe]:{type:"compel",id:qe,prompt:r},[Le]:{type:"noise",id:Le,width:l,height:u,use_cpu:p},[dn]:{type:"t2l",id:dn,cfg_scale:o,scheduler:s,steps:a},[nt]:{type:"l2i",id:nt,fp32:h==="fp32"}},edges:[{source:{node_id:pt,field:"clip"},destination:{node_id:rt,field:"clip"}},{source:{node_id:pt,field:"unet"},destination:{node_id:dn,field:"unet"}},{source:{node_id:rt,field:"clip"},destination:{node_id:Fe,field:"clip"}},{source:{node_id:rt,field:"clip"},destination:{node_id:qe,field:"clip"}},{source:{node_id:Fe,field:"conditioning"},destination:{node_id:dn,field:"positive_conditioning"}},{source:{node_id:qe,field:"conditioning"},destination:{node_id:dn,field:"negative_conditioning"}},{source:{node_id:dn,field:"latents"},destination:{node_id:nt,field:"latents"}},{source:{node_id:Le,field:"noise"},destination:{node_id:dn,field:"noise"}}]};return m.nodes[lt]={id:lt,type:"metadata_accumulator",generation_mode:"txt2img",cfg_scale:o,height:u,width:l,positive_prompt:"",negative_prompt:r,model:i,seed:0,steps:a,rand_device:p?"cpu":"cuda",scheduler:s,vae:void 0,controlnets:[],loras:[],clip_skip:c},Mh(e,m,dn),Nh(e,m),xc(e,m),Kv(e,m,dn),e.system.shouldUseNSFWChecker&&xl(e,m),e.system.shouldUseWatermarker&&Cl(e,m),m},Bpe=()=>{le({predicate:e=>Ph.match(e)&&e.payload==="txt2img",effect:async(e,{getState:t,dispatch:n,take:r})=>{const i=fe("session"),o=t(),s=o.generation.model;let a;s&&s.base_model==="sdxl"?a=$pe(o):a=Fpe(o),n(qM(a)),i.debug({graph:ra(a)},"Text to Image graph built"),n(On({graph:a})),await r(On.fulfilled.match),n(pl())}})},zN=Wk(),le=zN.startListening;Yle();Qle();eue();zle();Ule();Gle();Hle();Sle();Xle();Tpe();Lpe();Bpe();Ape();que();Dle();Ile();Ole();Nle();sce();ple();Xue();Yue();Zue();Jue();tce();Wue();Kue();ice();oce();nce();rce();ece();jue();Vue();zue();Uue();Gue();Hue();$ue();Fue();Bue();Fle();$le();Ble();jle();Wle();Kle();_le();Rue();qle();tue();vle();rue();mle();gle();pce();lce();const jpe={canvas:zQ,gallery:lJ,generation:SQ,nodes:qse,postprocessing:Wse,system:Sae,config:oY,ui:wQ,hotkeys:Cae,controlNet:rJ,boards:aJ,dynamicPrompts:oJ,imageDeletion:fJ,lora:pJ,modelmanager:xae,sdxl:Yse,[Hs.reducerPath]:Hs.reducer},Vpe=pc(jpe),zpe=Xae(Vpe),Upe=["canvas","gallery","generation","sdxl","nodes","postprocessing","system","ui","controlNet","dynamicPrompts","lora","modelmanager"],Gpe=Pk({reducer:zpe,enhancers:e=>e.concat(Yae(window.localStorage,Upe,{persistDebounce:300,serialize:ale,unserialize:ule,prefix:Qae})).concat(Xk()),middleware:e=>e({immutableCheck:!1,serializableCheck:!1}).concat(Hs.middleware).concat(Aae).prepend(zN.middleware),devTools:{actionSanitizer:dle,stateSanitizer:hle,trace:!0,predicate:(e,t)=>!fle.includes(t.type)}}),o4e=e=>e;function Hpe(e){if(e.sheet)return e.sheet;for(var t=0;t0?Pn(Cc,--Sr):0,lc--,Xt===10&&(lc=1,Yv--),Xt}function Ar(){return Xt=Sr2||Vf(Xt)>3?"":" "}function ige(e,t){for(;--t&&Ar()&&!(Xt<48||Xt>102||Xt>57&&Xt<65||Xt>70&&Xt<97););return Dh(e,_g()+(t<6&&Zi()==32&&Ar()==32))}function T2(e){for(;Ar();)switch(Xt){case e:return Sr;case 34:case 39:e!==34&&e!==39&&T2(Xt);break;case 40:e===41&&T2(e);break;case 92:Ar();break}return Sr}function oge(e,t){for(;Ar()&&e+Xt!==47+10;)if(e+Xt===42+42&&Zi()===47)break;return"/*"+Dh(t,Sr-1)+"*"+Xv(e===47?e:Ar())}function sge(e){for(;!Vf(Zi());)Ar();return Dh(e,Sr)}function age(e){return KN(xg("",null,null,null,[""],e=WN(e),0,[0],e))}function xg(e,t,n,r,i,o,s,a,l){for(var u=0,c=0,d=s,f=0,h=0,p=0,m=1,S=1,v=1,y=0,g="",b=i,_=o,w=r,x=g;S;)switch(p=y,y=Ar()){case 40:if(p!=108&&Pn(x,d-1)==58){C2(x+=He(wg(y),"&","&\f"),"&\f")!=-1&&(v=-1);break}case 34:case 39:case 91:x+=wg(y);break;case 9:case 10:case 13:case 32:x+=rge(p);break;case 92:x+=ige(_g()-1,7);continue;case 47:switch(Zi()){case 42:case 47:Vp(lge(oge(Ar(),_g()),t,n),l);break;default:x+="/"}break;case 123*m:a[u++]=Bi(x)*v;case 125*m:case 59:case 0:switch(y){case 0:case 125:S=0;case 59+c:v==-1&&(x=He(x,/\f/g,"")),h>0&&Bi(x)-d&&Vp(h>32?M6(x+";",r,n,d-1):M6(He(x," ","")+";",r,n,d-2),l);break;case 59:x+=";";default:if(Vp(w=I6(x,t,n,u,c,i,a,g,b=[],_=[],d),o),y===123)if(c===0)xg(x,t,w,w,b,o,d,a,_);else switch(f===99&&Pn(x,3)===110?100:f){case 100:case 108:case 109:case 115:xg(e,w,w,r&&Vp(I6(e,w,w,0,0,i,a,g,i,b=[],d),_),i,_,d,a,r?b:_);break;default:xg(x,w,w,w,[""],_,0,a,_)}}u=c=h=0,m=v=1,g=x="",d=s;break;case 58:d=1+Bi(x),h=p;default:if(m<1){if(y==123)--m;else if(y==125&&m++==0&&nge()==125)continue}switch(x+=Xv(y),y*m){case 38:v=c>0?1:(x+="\f",-1);break;case 44:a[u++]=(Bi(x)-1)*v,v=1;break;case 64:Zi()===45&&(x+=wg(Ar())),f=Zi(),c=d=Bi(g=x+=sge(_g())),y++;break;case 45:p===45&&Bi(x)==2&&(m=0)}}return o}function I6(e,t,n,r,i,o,s,a,l,u,c){for(var d=i-1,f=i===0?o:[""],h=$C(f),p=0,m=0,S=0;p0?f[v]+" "+y:He(y,/&\f/g,f[v])))&&(l[S++]=g);return Qv(e,t,n,i===0?DC:a,l,u,c)}function lge(e,t,n){return Qv(e,t,n,UN,Xv(tge()),jf(e,2,-2),0)}function M6(e,t,n,r){return Qv(e,t,n,LC,jf(e,0,r),jf(e,r+1,-1),r)}function Lu(e,t){for(var n="",r=$C(e),i=0;i6)switch(Pn(e,t+1)){case 109:if(Pn(e,t+4)!==45)break;case 102:return He(e,/(.+:)(.+)-([^]+)/,"$1"+Ge+"$2-$3$1"+ey+(Pn(e,t+3)==108?"$3":"$2-$3"))+e;case 115:return~C2(e,"stretch")?YN(He(e,"stretch","fill-available"),t)+e:e}break;case 4949:if(Pn(e,t+1)!==115)break;case 6444:switch(Pn(e,Bi(e)-3-(~C2(e,"!important")&&10))){case 107:return He(e,":",":"+Ge)+e;case 101:return He(e,/(.+:)([^;!]+)(;|!.+)?/,"$1"+Ge+(Pn(e,14)===45?"inline-":"")+"box$3$1"+Ge+"$2$3$1"+Dn+"$2box$3")+e}break;case 5936:switch(Pn(e,t+11)){case 114:return Ge+e+Dn+He(e,/[svh]\w+-[tblr]{2}/,"tb")+e;case 108:return Ge+e+Dn+He(e,/[svh]\w+-[tblr]{2}/,"tb-rl")+e;case 45:return Ge+e+Dn+He(e,/[svh]\w+-[tblr]{2}/,"lr")+e}return Ge+e+Dn+e+e}return e}var yge=function(t,n,r,i){if(t.length>-1&&!t.return)switch(t.type){case LC:t.return=YN(t.value,t.length);break;case GN:return Lu([rd(t,{value:He(t.value,"@","@"+Ge)})],i);case DC:if(t.length)return ege(t.props,function(o){switch(Jpe(o,/(::plac\w+|:read-\w+)/)){case":read-only":case":read-write":return Lu([rd(t,{props:[He(o,/:(read-\w+)/,":"+ey+"$1")]})],i);case"::placeholder":return Lu([rd(t,{props:[He(o,/:(plac\w+)/,":"+Ge+"input-$1")]}),rd(t,{props:[He(o,/:(plac\w+)/,":"+ey+"$1")]}),rd(t,{props:[He(o,/:(plac\w+)/,Dn+"input-$1")]})],i)}return""})}},vge=[yge],bge=function(t){var n=t.key;if(n==="css"){var r=document.querySelectorAll("style[data-emotion]:not([data-s])");Array.prototype.forEach.call(r,function(m){var S=m.getAttribute("data-emotion");S.indexOf(" ")!==-1&&(document.head.appendChild(m),m.setAttribute("data-s",""))})}var i=t.stylisPlugins||vge,o={},s,a=[];s=t.container||document.head,Array.prototype.forEach.call(document.querySelectorAll('style[data-emotion^="'+n+' "]'),function(m){for(var S=m.getAttribute("data-emotion").split(" "),v=1;v=4;++r,i-=4)n=e.charCodeAt(r)&255|(e.charCodeAt(++r)&255)<<8|(e.charCodeAt(++r)&255)<<16|(e.charCodeAt(++r)&255)<<24,n=(n&65535)*1540483477+((n>>>16)*59797<<16),n^=n>>>24,t=(n&65535)*1540483477+((n>>>16)*59797<<16)^(t&65535)*1540483477+((t>>>16)*59797<<16);switch(i){case 3:t^=(e.charCodeAt(r+2)&255)<<16;case 2:t^=(e.charCodeAt(r+1)&255)<<8;case 1:t^=e.charCodeAt(r)&255,t=(t&65535)*1540483477+((t>>>16)*59797<<16)}return t^=t>>>13,t=(t&65535)*1540483477+((t>>>16)*59797<<16),((t^t>>>15)>>>0).toString(36)}var xge={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1},Cge=/[A-Z]|^ms/g,Tge=/_EMO_([^_]+?)_([^]*?)_EMO_/g,JN=function(t){return t.charCodeAt(1)===45},L6=function(t){return t!=null&&typeof t!="boolean"},Jb=XN(function(e){return JN(e)?e:e.replace(Cge,"-$&").toLowerCase()}),$6=function(t,n){switch(t){case"animation":case"animationName":if(typeof n=="string")return n.replace(Tge,function(r,i,o){return ji={name:i,styles:o,next:ji},i})}return xge[t]!==1&&!JN(t)&&typeof n=="number"&&n!==0?n+"px":n};function zf(e,t,n){if(n==null)return"";if(n.__emotion_styles!==void 0)return n;switch(typeof n){case"boolean":return"";case"object":{if(n.anim===1)return ji={name:n.name,styles:n.styles,next:ji},n.name;if(n.styles!==void 0){var r=n.next;if(r!==void 0)for(;r!==void 0;)ji={name:r.name,styles:r.styles,next:ji},r=r.next;var i=n.styles+";";return i}return Ege(e,t,n)}case"function":{if(e!==void 0){var o=ji,s=n(e);return ji=o,zf(e,t,s)}break}}if(t==null)return n;var a=t[n];return a!==void 0?a:n}function Ege(e,t,n){var r="";if(Array.isArray(n))for(var i=0;i` or ``");return e}var iD=k.createContext({});iD.displayName="ColorModeContext";function BC(){const e=k.useContext(iD);if(e===void 0)throw new Error("useColorMode must be used within a ColorModeProvider");return e}function l4e(e,t){const{colorMode:n}=BC();return n==="dark"?t:e}function Nge(){const e=BC(),t=rD();return{...e,theme:t}}function Dge(e,t,n){var r,i;if(t==null)return t;const o=s=>{var a,l;return(l=(a=e.__breakpoints)==null?void 0:a.asArray)==null?void 0:l[s]};return(i=(r=o(t))!=null?r:o(n))!=null?i:n}function Lge(e,t,n){var r,i;if(t==null)return t;const o=s=>{var a,l;return(l=(a=e.__cssMap)==null?void 0:a[s])==null?void 0:l.value};return(i=(r=o(t))!=null?r:o(n))!=null?i:n}function u4e(e,t,n){const r=rD();return $ge(e,t,n)(r)}function $ge(e,t,n){const r=Array.isArray(t)?t:[t],i=Array.isArray(n)?n:[n];return o=>{const s=i.filter(Boolean),a=r.map((l,u)=>{var c,d;if(e==="breakpoints")return Dge(o,l,(c=s[u])!=null?c:l);const f=`${e}.${l}`;return Lge(o,f,(d=s[u])!=null?d:l)});return Array.isArray(t)?a:a[0]}}var oD=(...e)=>e.filter(Boolean).join(" ");function Fge(){return!1}function Io(e){const t=typeof e;return e!=null&&(t==="object"||t==="function")&&!Array.isArray(e)}var c4e=e=>{const{condition:t,message:n}=e;t&&Fge()&&console.warn(n)};function Na(e,...t){return Bge(e)?e(...t):e}var Bge=e=>typeof e=="function",d4e=e=>e?"":void 0,f4e=e=>e?!0:void 0;function h4e(...e){return function(n){e.some(r=>(r==null||r(n),n==null?void 0:n.defaultPrevented))}}function p4e(...e){return function(n){e.forEach(r=>{r==null||r(n)})}}var ty={exports:{}};ty.exports;(function(e,t){var n=200,r="__lodash_hash_undefined__",i=800,o=16,s=9007199254740991,a="[object Arguments]",l="[object Array]",u="[object AsyncFunction]",c="[object Boolean]",d="[object Date]",f="[object Error]",h="[object Function]",p="[object GeneratorFunction]",m="[object Map]",S="[object Number]",v="[object Null]",y="[object Object]",g="[object Proxy]",b="[object RegExp]",_="[object Set]",w="[object String]",x="[object Undefined]",T="[object WeakMap]",P="[object ArrayBuffer]",E="[object DataView]",A="[object Float32Array]",$="[object Float64Array]",M="[object Int8Array]",C="[object Int16Array]",O="[object Int32Array]",I="[object Uint8Array]",N="[object Uint8ClampedArray]",R="[object Uint16Array]",D="[object Uint32Array]",L=/[\\^$.*+?()[\]{}|]/g,j=/^\[object .+?Constructor\]$/,U=/^(?:0|[1-9]\d*)$/,G={};G[A]=G[$]=G[M]=G[C]=G[O]=G[I]=G[N]=G[R]=G[D]=!0,G[a]=G[l]=G[P]=G[c]=G[E]=G[d]=G[f]=G[h]=G[m]=G[S]=G[y]=G[b]=G[_]=G[w]=G[T]=!1;var W=typeof Ee=="object"&&Ee&&Ee.Object===Object&&Ee,X=typeof self=="object"&&self&&self.Object===Object&&self,Y=W||X||Function("return this")(),B=t&&!t.nodeType&&t,H=B&&!0&&e&&!e.nodeType&&e,Q=H&&H.exports===B,J=Q&&W.process,ne=function(){try{var F=H&&H.require&&H.require("util").types;return F||J&&J.binding&&J.binding("util")}catch{}}(),te=ne&&ne.isTypedArray;function xe(F,V,q){switch(q.length){case 0:return F.call(V);case 1:return F.call(V,q[0]);case 2:return F.call(V,q[0],q[1]);case 3:return F.call(V,q[0],q[1],q[2])}return F.apply(V,q)}function ve(F,V){for(var q=-1,ie=Array(F);++q-1}function fo(F,V){var q=this.__data__,ie=kl(q,F);return ie<0?(++this.size,q.push([F,V])):q[ie][1]=V,this}wn.prototype.clear=co,wn.prototype.delete=Zo,wn.prototype.get=Jo,wn.prototype.has=Al,wn.prototype.set=fo;function qn(F){var V=-1,q=F==null?0:F.length;for(this.clear();++V1?q[De-1]:void 0,mt=De>2?q[2]:void 0;for(tt=F.length>3&&typeof tt=="function"?(De--,tt):void 0,mt&&V$(q[0],q[1],mt)&&(tt=De<3?void 0:tt,De=1),V=Object(V);++ie-1&&F%1==0&&F0){if(++V>=i)return arguments[0]}else V=0;return F.apply(void 0,arguments)}}function X$(F){if(F!=null){try{return Je.call(F)}catch{}try{return F+""}catch{}}return""}function Kh(F,V){return F===V||F!==F&&V!==V}var P1=qh(function(){return arguments}())?qh:function(F){return Oc(F)&&Gt.call(F,"callee")&&!ri.call(F,"callee")},A1=Array.isArray;function k1(F){return F!=null&&k3(F.length)&&!O1(F)}function Y$(F){return Oc(F)&&k1(F)}var A3=ca||tF;function O1(F){if(!ha(F))return!1;var V=Rl(F);return V==h||V==p||V==u||V==g}function k3(F){return typeof F=="number"&&F>-1&&F%1==0&&F<=s}function ha(F){var V=typeof F;return F!=null&&(V=="object"||V=="function")}function Oc(F){return F!=null&&typeof F=="object"}function Q$(F){if(!Oc(F)||Rl(F)!=y)return!1;var V=wr(F);if(V===null)return!0;var q=Gt.call(V,"constructor")&&V.constructor;return typeof q=="function"&&q instanceof q&&Je.call(q)==Lr}var O3=te?ce(te):kc;function Z$(F){return L$(F,R3(F))}function R3(F){return k1(F)?_1(F,!0):A$(F)}var J$=$$(function(F,V,q,ie){T3(F,V,q,ie)});function eF(F){return function(){return F}}function I3(F){return F}function tF(){return!1}e.exports=J$})(ty,ty.exports);var jge=ty.exports;const Wi=al(jge);var Vge=e=>/!(important)?$/.test(e),j6=e=>typeof e=="string"?e.replace(/!(important)?$/,"").trim():e,zge=(e,t)=>n=>{const r=String(t),i=Vge(r),o=j6(r),s=e?`${e}.${o}`:o;let a=Io(n.__cssMap)&&s in n.__cssMap?n.__cssMap[s].varRef:t;return a=j6(a),i?`${a} !important`:a};function jC(e){const{scale:t,transform:n,compose:r}=e;return(o,s)=>{var a;const l=zge(t,o)(s);let u=(a=n==null?void 0:n(l,s))!=null?a:l;return r&&(u=r(u,s)),u}}var zp=(...e)=>t=>e.reduce((n,r)=>r(n),t);function jr(e,t){return n=>{const r={property:n,scale:e};return r.transform=jC({scale:e,transform:t}),r}}var Uge=({rtl:e,ltr:t})=>n=>n.direction==="rtl"?e:t;function Gge(e){const{property:t,scale:n,transform:r}=e;return{scale:n,property:Uge(t),transform:n?jC({scale:n,compose:r}):r}}var sD=["rotate(var(--chakra-rotate, 0))","scaleX(var(--chakra-scale-x, 1))","scaleY(var(--chakra-scale-y, 1))","skewX(var(--chakra-skew-x, 0))","skewY(var(--chakra-skew-y, 0))"];function Hge(){return["translateX(var(--chakra-translate-x, 0))","translateY(var(--chakra-translate-y, 0))",...sD].join(" ")}function qge(){return["translate3d(var(--chakra-translate-x, 0), var(--chakra-translate-y, 0), 0)",...sD].join(" ")}var Wge={"--chakra-blur":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-brightness":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-contrast":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-grayscale":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-hue-rotate":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-invert":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-saturate":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-sepia":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-drop-shadow":"var(--chakra-empty,/*!*/ /*!*/)",filter:["var(--chakra-blur)","var(--chakra-brightness)","var(--chakra-contrast)","var(--chakra-grayscale)","var(--chakra-hue-rotate)","var(--chakra-invert)","var(--chakra-saturate)","var(--chakra-sepia)","var(--chakra-drop-shadow)"].join(" ")},Kge={backdropFilter:["var(--chakra-backdrop-blur)","var(--chakra-backdrop-brightness)","var(--chakra-backdrop-contrast)","var(--chakra-backdrop-grayscale)","var(--chakra-backdrop-hue-rotate)","var(--chakra-backdrop-invert)","var(--chakra-backdrop-opacity)","var(--chakra-backdrop-saturate)","var(--chakra-backdrop-sepia)"].join(" "),"--chakra-backdrop-blur":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-backdrop-brightness":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-backdrop-contrast":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-backdrop-grayscale":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-backdrop-hue-rotate":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-backdrop-invert":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-backdrop-opacity":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-backdrop-saturate":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-backdrop-sepia":"var(--chakra-empty,/*!*/ /*!*/)"};function Xge(e){return{"--chakra-ring-offset-shadow":"var(--chakra-ring-inset) 0 0 0 var(--chakra-ring-offset-width) var(--chakra-ring-offset-color)","--chakra-ring-shadow":"var(--chakra-ring-inset) 0 0 0 calc(var(--chakra-ring-width) + var(--chakra-ring-offset-width)) var(--chakra-ring-color)","--chakra-ring-width":e,boxShadow:["var(--chakra-ring-offset-shadow)","var(--chakra-ring-shadow)","var(--chakra-shadow, 0 0 #0000)"].join(", ")}}var Yge={"row-reverse":{space:"--chakra-space-x-reverse",divide:"--chakra-divide-x-reverse"},"column-reverse":{space:"--chakra-space-y-reverse",divide:"--chakra-divide-y-reverse"}},E2={"to-t":"to top","to-tr":"to top right","to-r":"to right","to-br":"to bottom right","to-b":"to bottom","to-bl":"to bottom left","to-l":"to left","to-tl":"to top left"},Qge=new Set(Object.values(E2)),P2=new Set(["none","-moz-initial","inherit","initial","revert","unset"]),Zge=e=>e.trim();function Jge(e,t){if(e==null||P2.has(e))return e;if(!(A2(e)||P2.has(e)))return`url('${e}')`;const i=/(^[a-z-A-Z]+)\((.*)\)/g.exec(e),o=i==null?void 0:i[1],s=i==null?void 0:i[2];if(!o||!s)return e;const a=o.includes("-gradient")?o:`${o}-gradient`,[l,...u]=s.split(",").map(Zge).filter(Boolean);if((u==null?void 0:u.length)===0)return e;const c=l in E2?E2[l]:l;u.unshift(c);const d=u.map(f=>{if(Qge.has(f))return f;const h=f.indexOf(" "),[p,m]=h!==-1?[f.substr(0,h),f.substr(h+1)]:[f],S=A2(m)?m:m&&m.split(" "),v=`colors.${p}`,y=v in t.__cssMap?t.__cssMap[v].varRef:p;return S?[y,...Array.isArray(S)?S:[S]].join(" "):y});return`${a}(${d.join(", ")})`}var A2=e=>typeof e=="string"&&e.includes("(")&&e.includes(")"),eme=(e,t)=>Jge(e,t??{});function tme(e){return/^var\(--.+\)$/.test(e)}var nme=e=>{const t=parseFloat(e.toString()),n=e.toString().replace(String(t),"");return{unitless:!n,value:t,unit:n}},Ii=e=>t=>`${e}(${t})`,je={filter(e){return e!=="auto"?e:Wge},backdropFilter(e){return e!=="auto"?e:Kge},ring(e){return Xge(je.px(e))},bgClip(e){return e==="text"?{color:"transparent",backgroundClip:"text"}:{backgroundClip:e}},transform(e){return e==="auto"?Hge():e==="auto-gpu"?qge():e},vh(e){return e==="$100vh"?"var(--chakra-vh)":e},px(e){if(e==null)return e;const{unitless:t}=nme(e);return t||typeof e=="number"?`${e}px`:e},fraction(e){return typeof e!="number"||e>1?e:`${e*100}%`},float(e,t){const n={left:"right",right:"left"};return t.direction==="rtl"?n[e]:e},degree(e){if(tme(e)||e==null)return e;const t=typeof e=="string"&&!e.endsWith("deg");return typeof e=="number"||t?`${e}deg`:e},gradient:eme,blur:Ii("blur"),opacity:Ii("opacity"),brightness:Ii("brightness"),contrast:Ii("contrast"),dropShadow:Ii("drop-shadow"),grayscale:Ii("grayscale"),hueRotate:Ii("hue-rotate"),invert:Ii("invert"),saturate:Ii("saturate"),sepia:Ii("sepia"),bgImage(e){return e==null||A2(e)||P2.has(e)?e:`url(${e})`},outline(e){const t=String(e)==="0"||String(e)==="none";return e!==null&&t?{outline:"2px solid transparent",outlineOffset:"2px"}:{outline:e}},flexDirection(e){var t;const{space:n,divide:r}=(t=Yge[e])!=null?t:{},i={flexDirection:e};return n&&(i[n]=1),r&&(i[r]=1),i}},z={borderWidths:jr("borderWidths"),borderStyles:jr("borderStyles"),colors:jr("colors"),borders:jr("borders"),gradients:jr("gradients",je.gradient),radii:jr("radii",je.px),space:jr("space",zp(je.vh,je.px)),spaceT:jr("space",zp(je.vh,je.px)),degreeT(e){return{property:e,transform:je.degree}},prop(e,t,n){return{property:e,scale:t,...t&&{transform:jC({scale:t,transform:n})}}},propT(e,t){return{property:e,transform:t}},sizes:jr("sizes",zp(je.vh,je.px)),sizesT:jr("sizes",zp(je.vh,je.fraction)),shadows:jr("shadows"),logical:Gge,blur:jr("blur",je.blur)},Cg={background:z.colors("background"),backgroundColor:z.colors("backgroundColor"),backgroundImage:z.gradients("backgroundImage"),backgroundSize:!0,backgroundPosition:!0,backgroundRepeat:!0,backgroundAttachment:!0,backgroundClip:{transform:je.bgClip},bgSize:z.prop("backgroundSize"),bgPosition:z.prop("backgroundPosition"),bg:z.colors("background"),bgColor:z.colors("backgroundColor"),bgPos:z.prop("backgroundPosition"),bgRepeat:z.prop("backgroundRepeat"),bgAttachment:z.prop("backgroundAttachment"),bgGradient:z.gradients("backgroundImage"),bgClip:{transform:je.bgClip}};Object.assign(Cg,{bgImage:Cg.backgroundImage,bgImg:Cg.backgroundImage});var Ue={border:z.borders("border"),borderWidth:z.borderWidths("borderWidth"),borderStyle:z.borderStyles("borderStyle"),borderColor:z.colors("borderColor"),borderRadius:z.radii("borderRadius"),borderTop:z.borders("borderTop"),borderBlockStart:z.borders("borderBlockStart"),borderTopLeftRadius:z.radii("borderTopLeftRadius"),borderStartStartRadius:z.logical({scale:"radii",property:{ltr:"borderTopLeftRadius",rtl:"borderTopRightRadius"}}),borderEndStartRadius:z.logical({scale:"radii",property:{ltr:"borderBottomLeftRadius",rtl:"borderBottomRightRadius"}}),borderTopRightRadius:z.radii("borderTopRightRadius"),borderStartEndRadius:z.logical({scale:"radii",property:{ltr:"borderTopRightRadius",rtl:"borderTopLeftRadius"}}),borderEndEndRadius:z.logical({scale:"radii",property:{ltr:"borderBottomRightRadius",rtl:"borderBottomLeftRadius"}}),borderRight:z.borders("borderRight"),borderInlineEnd:z.borders("borderInlineEnd"),borderBottom:z.borders("borderBottom"),borderBlockEnd:z.borders("borderBlockEnd"),borderBottomLeftRadius:z.radii("borderBottomLeftRadius"),borderBottomRightRadius:z.radii("borderBottomRightRadius"),borderLeft:z.borders("borderLeft"),borderInlineStart:{property:"borderInlineStart",scale:"borders"},borderInlineStartRadius:z.logical({scale:"radii",property:{ltr:["borderTopLeftRadius","borderBottomLeftRadius"],rtl:["borderTopRightRadius","borderBottomRightRadius"]}}),borderInlineEndRadius:z.logical({scale:"radii",property:{ltr:["borderTopRightRadius","borderBottomRightRadius"],rtl:["borderTopLeftRadius","borderBottomLeftRadius"]}}),borderX:z.borders(["borderLeft","borderRight"]),borderInline:z.borders("borderInline"),borderY:z.borders(["borderTop","borderBottom"]),borderBlock:z.borders("borderBlock"),borderTopWidth:z.borderWidths("borderTopWidth"),borderBlockStartWidth:z.borderWidths("borderBlockStartWidth"),borderTopColor:z.colors("borderTopColor"),borderBlockStartColor:z.colors("borderBlockStartColor"),borderTopStyle:z.borderStyles("borderTopStyle"),borderBlockStartStyle:z.borderStyles("borderBlockStartStyle"),borderBottomWidth:z.borderWidths("borderBottomWidth"),borderBlockEndWidth:z.borderWidths("borderBlockEndWidth"),borderBottomColor:z.colors("borderBottomColor"),borderBlockEndColor:z.colors("borderBlockEndColor"),borderBottomStyle:z.borderStyles("borderBottomStyle"),borderBlockEndStyle:z.borderStyles("borderBlockEndStyle"),borderLeftWidth:z.borderWidths("borderLeftWidth"),borderInlineStartWidth:z.borderWidths("borderInlineStartWidth"),borderLeftColor:z.colors("borderLeftColor"),borderInlineStartColor:z.colors("borderInlineStartColor"),borderLeftStyle:z.borderStyles("borderLeftStyle"),borderInlineStartStyle:z.borderStyles("borderInlineStartStyle"),borderRightWidth:z.borderWidths("borderRightWidth"),borderInlineEndWidth:z.borderWidths("borderInlineEndWidth"),borderRightColor:z.colors("borderRightColor"),borderInlineEndColor:z.colors("borderInlineEndColor"),borderRightStyle:z.borderStyles("borderRightStyle"),borderInlineEndStyle:z.borderStyles("borderInlineEndStyle"),borderTopRadius:z.radii(["borderTopLeftRadius","borderTopRightRadius"]),borderBottomRadius:z.radii(["borderBottomLeftRadius","borderBottomRightRadius"]),borderLeftRadius:z.radii(["borderTopLeftRadius","borderBottomLeftRadius"]),borderRightRadius:z.radii(["borderTopRightRadius","borderBottomRightRadius"])};Object.assign(Ue,{rounded:Ue.borderRadius,roundedTop:Ue.borderTopRadius,roundedTopLeft:Ue.borderTopLeftRadius,roundedTopRight:Ue.borderTopRightRadius,roundedTopStart:Ue.borderStartStartRadius,roundedTopEnd:Ue.borderStartEndRadius,roundedBottom:Ue.borderBottomRadius,roundedBottomLeft:Ue.borderBottomLeftRadius,roundedBottomRight:Ue.borderBottomRightRadius,roundedBottomStart:Ue.borderEndStartRadius,roundedBottomEnd:Ue.borderEndEndRadius,roundedLeft:Ue.borderLeftRadius,roundedRight:Ue.borderRightRadius,roundedStart:Ue.borderInlineStartRadius,roundedEnd:Ue.borderInlineEndRadius,borderStart:Ue.borderInlineStart,borderEnd:Ue.borderInlineEnd,borderTopStartRadius:Ue.borderStartStartRadius,borderTopEndRadius:Ue.borderStartEndRadius,borderBottomStartRadius:Ue.borderEndStartRadius,borderBottomEndRadius:Ue.borderEndEndRadius,borderStartRadius:Ue.borderInlineStartRadius,borderEndRadius:Ue.borderInlineEndRadius,borderStartWidth:Ue.borderInlineStartWidth,borderEndWidth:Ue.borderInlineEndWidth,borderStartColor:Ue.borderInlineStartColor,borderEndColor:Ue.borderInlineEndColor,borderStartStyle:Ue.borderInlineStartStyle,borderEndStyle:Ue.borderInlineEndStyle});var rme={color:z.colors("color"),textColor:z.colors("color"),fill:z.colors("fill"),stroke:z.colors("stroke")},k2={boxShadow:z.shadows("boxShadow"),mixBlendMode:!0,blendMode:z.prop("mixBlendMode"),backgroundBlendMode:!0,bgBlendMode:z.prop("backgroundBlendMode"),opacity:!0};Object.assign(k2,{shadow:k2.boxShadow});var ime={filter:{transform:je.filter},blur:z.blur("--chakra-blur"),brightness:z.propT("--chakra-brightness",je.brightness),contrast:z.propT("--chakra-contrast",je.contrast),hueRotate:z.degreeT("--chakra-hue-rotate"),invert:z.propT("--chakra-invert",je.invert),saturate:z.propT("--chakra-saturate",je.saturate),dropShadow:z.propT("--chakra-drop-shadow",je.dropShadow),backdropFilter:{transform:je.backdropFilter},backdropBlur:z.blur("--chakra-backdrop-blur"),backdropBrightness:z.propT("--chakra-backdrop-brightness",je.brightness),backdropContrast:z.propT("--chakra-backdrop-contrast",je.contrast),backdropHueRotate:z.degreeT("--chakra-backdrop-hue-rotate"),backdropInvert:z.propT("--chakra-backdrop-invert",je.invert),backdropSaturate:z.propT("--chakra-backdrop-saturate",je.saturate)},ny={alignItems:!0,alignContent:!0,justifyItems:!0,justifyContent:!0,flexWrap:!0,flexDirection:{transform:je.flexDirection},flex:!0,flexFlow:!0,flexGrow:!0,flexShrink:!0,flexBasis:z.sizes("flexBasis"),justifySelf:!0,alignSelf:!0,order:!0,placeItems:!0,placeContent:!0,placeSelf:!0,gap:z.space("gap"),rowGap:z.space("rowGap"),columnGap:z.space("columnGap")};Object.assign(ny,{flexDir:ny.flexDirection});var aD={gridGap:z.space("gridGap"),gridColumnGap:z.space("gridColumnGap"),gridRowGap:z.space("gridRowGap"),gridColumn:!0,gridRow:!0,gridAutoFlow:!0,gridAutoColumns:!0,gridColumnStart:!0,gridColumnEnd:!0,gridRowStart:!0,gridRowEnd:!0,gridAutoRows:!0,gridTemplate:!0,gridTemplateColumns:!0,gridTemplateRows:!0,gridTemplateAreas:!0,gridArea:!0},ome={appearance:!0,cursor:!0,resize:!0,userSelect:!0,pointerEvents:!0,outline:{transform:je.outline},outlineOffset:!0,outlineColor:z.colors("outlineColor")},zr={width:z.sizesT("width"),inlineSize:z.sizesT("inlineSize"),height:z.sizes("height"),blockSize:z.sizes("blockSize"),boxSize:z.sizes(["width","height"]),minWidth:z.sizes("minWidth"),minInlineSize:z.sizes("minInlineSize"),minHeight:z.sizes("minHeight"),minBlockSize:z.sizes("minBlockSize"),maxWidth:z.sizes("maxWidth"),maxInlineSize:z.sizes("maxInlineSize"),maxHeight:z.sizes("maxHeight"),maxBlockSize:z.sizes("maxBlockSize"),overflow:!0,overflowX:!0,overflowY:!0,overscrollBehavior:!0,overscrollBehaviorX:!0,overscrollBehaviorY:!0,display:!0,aspectRatio:!0,hideFrom:{scale:"breakpoints",transform:(e,t)=>{var n,r,i;return{[`@media screen and (min-width: ${(i=(r=(n=t.__breakpoints)==null?void 0:n.get(e))==null?void 0:r.minW)!=null?i:e})`]:{display:"none"}}}},hideBelow:{scale:"breakpoints",transform:(e,t)=>{var n,r,i;return{[`@media screen and (max-width: ${(i=(r=(n=t.__breakpoints)==null?void 0:n.get(e))==null?void 0:r._minW)!=null?i:e})`]:{display:"none"}}}},verticalAlign:!0,boxSizing:!0,boxDecorationBreak:!0,float:z.propT("float",je.float),objectFit:!0,objectPosition:!0,visibility:!0,isolation:!0};Object.assign(zr,{w:zr.width,h:zr.height,minW:zr.minWidth,maxW:zr.maxWidth,minH:zr.minHeight,maxH:zr.maxHeight,overscroll:zr.overscrollBehavior,overscrollX:zr.overscrollBehaviorX,overscrollY:zr.overscrollBehaviorY});var sme={listStyleType:!0,listStylePosition:!0,listStylePos:z.prop("listStylePosition"),listStyleImage:!0,listStyleImg:z.prop("listStyleImage")};function ame(e,t,n,r){const i=typeof t=="string"?t.split("."):[t];for(r=0;r{const t=new WeakMap;return(r,i,o,s)=>{if(typeof r>"u")return e(r,i,o);t.has(r)||t.set(r,new Map);const a=t.get(r);if(a.has(i))return a.get(i);const l=e(r,i,o,s);return a.set(i,l),l}},ume=lme(ame),cme={border:"0px",clip:"rect(0, 0, 0, 0)",width:"1px",height:"1px",margin:"-1px",padding:"0px",overflow:"hidden",whiteSpace:"nowrap",position:"absolute"},dme={position:"static",width:"auto",height:"auto",clip:"auto",padding:"0",margin:"0",overflow:"visible",whiteSpace:"normal"},eS=(e,t,n)=>{const r={},i=ume(e,t,{});for(const o in i)o in n&&n[o]!=null||(r[o]=i[o]);return r},fme={srOnly:{transform(e){return e===!0?cme:e==="focusable"?dme:{}}},layerStyle:{processResult:!0,transform:(e,t,n)=>eS(t,`layerStyles.${e}`,n)},textStyle:{processResult:!0,transform:(e,t,n)=>eS(t,`textStyles.${e}`,n)},apply:{processResult:!0,transform:(e,t,n)=>eS(t,e,n)}},Od={position:!0,pos:z.prop("position"),zIndex:z.prop("zIndex","zIndices"),inset:z.spaceT("inset"),insetX:z.spaceT(["left","right"]),insetInline:z.spaceT("insetInline"),insetY:z.spaceT(["top","bottom"]),insetBlock:z.spaceT("insetBlock"),top:z.spaceT("top"),insetBlockStart:z.spaceT("insetBlockStart"),bottom:z.spaceT("bottom"),insetBlockEnd:z.spaceT("insetBlockEnd"),left:z.spaceT("left"),insetInlineStart:z.logical({scale:"space",property:{ltr:"left",rtl:"right"}}),right:z.spaceT("right"),insetInlineEnd:z.logical({scale:"space",property:{ltr:"right",rtl:"left"}})};Object.assign(Od,{insetStart:Od.insetInlineStart,insetEnd:Od.insetInlineEnd});var hme={ring:{transform:je.ring},ringColor:z.colors("--chakra-ring-color"),ringOffset:z.prop("--chakra-ring-offset-width"),ringOffsetColor:z.colors("--chakra-ring-offset-color"),ringInset:z.prop("--chakra-ring-inset")},dt={margin:z.spaceT("margin"),marginTop:z.spaceT("marginTop"),marginBlockStart:z.spaceT("marginBlockStart"),marginRight:z.spaceT("marginRight"),marginInlineEnd:z.spaceT("marginInlineEnd"),marginBottom:z.spaceT("marginBottom"),marginBlockEnd:z.spaceT("marginBlockEnd"),marginLeft:z.spaceT("marginLeft"),marginInlineStart:z.spaceT("marginInlineStart"),marginX:z.spaceT(["marginInlineStart","marginInlineEnd"]),marginInline:z.spaceT("marginInline"),marginY:z.spaceT(["marginTop","marginBottom"]),marginBlock:z.spaceT("marginBlock"),padding:z.space("padding"),paddingTop:z.space("paddingTop"),paddingBlockStart:z.space("paddingBlockStart"),paddingRight:z.space("paddingRight"),paddingBottom:z.space("paddingBottom"),paddingBlockEnd:z.space("paddingBlockEnd"),paddingLeft:z.space("paddingLeft"),paddingInlineStart:z.space("paddingInlineStart"),paddingInlineEnd:z.space("paddingInlineEnd"),paddingX:z.space(["paddingInlineStart","paddingInlineEnd"]),paddingInline:z.space("paddingInline"),paddingY:z.space(["paddingTop","paddingBottom"]),paddingBlock:z.space("paddingBlock")};Object.assign(dt,{m:dt.margin,mt:dt.marginTop,mr:dt.marginRight,me:dt.marginInlineEnd,marginEnd:dt.marginInlineEnd,mb:dt.marginBottom,ml:dt.marginLeft,ms:dt.marginInlineStart,marginStart:dt.marginInlineStart,mx:dt.marginX,my:dt.marginY,p:dt.padding,pt:dt.paddingTop,py:dt.paddingY,px:dt.paddingX,pb:dt.paddingBottom,pl:dt.paddingLeft,ps:dt.paddingInlineStart,paddingStart:dt.paddingInlineStart,pr:dt.paddingRight,pe:dt.paddingInlineEnd,paddingEnd:dt.paddingInlineEnd});var pme={textDecorationColor:z.colors("textDecorationColor"),textDecoration:!0,textDecor:{property:"textDecoration"},textDecorationLine:!0,textDecorationStyle:!0,textDecorationThickness:!0,textUnderlineOffset:!0,textShadow:z.shadows("textShadow")},gme={clipPath:!0,transform:z.propT("transform",je.transform),transformOrigin:!0,translateX:z.spaceT("--chakra-translate-x"),translateY:z.spaceT("--chakra-translate-y"),skewX:z.degreeT("--chakra-skew-x"),skewY:z.degreeT("--chakra-skew-y"),scaleX:z.prop("--chakra-scale-x"),scaleY:z.prop("--chakra-scale-y"),scale:z.prop(["--chakra-scale-x","--chakra-scale-y"]),rotate:z.degreeT("--chakra-rotate")},mme={transition:!0,transitionDelay:!0,animation:!0,willChange:!0,transitionDuration:z.prop("transitionDuration","transition.duration"),transitionProperty:z.prop("transitionProperty","transition.property"),transitionTimingFunction:z.prop("transitionTimingFunction","transition.easing")},yme={fontFamily:z.prop("fontFamily","fonts"),fontSize:z.prop("fontSize","fontSizes",je.px),fontWeight:z.prop("fontWeight","fontWeights"),lineHeight:z.prop("lineHeight","lineHeights"),letterSpacing:z.prop("letterSpacing","letterSpacings"),textAlign:!0,fontStyle:!0,textIndent:!0,wordBreak:!0,overflowWrap:!0,textOverflow:!0,textTransform:!0,whiteSpace:!0,isTruncated:{transform(e){if(e===!0)return{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}},noOfLines:{static:{overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:"var(--chakra-line-clamp)"},property:"--chakra-line-clamp"}},vme={scrollBehavior:!0,scrollSnapAlign:!0,scrollSnapStop:!0,scrollSnapType:!0,scrollMargin:z.spaceT("scrollMargin"),scrollMarginTop:z.spaceT("scrollMarginTop"),scrollMarginBottom:z.spaceT("scrollMarginBottom"),scrollMarginLeft:z.spaceT("scrollMarginLeft"),scrollMarginRight:z.spaceT("scrollMarginRight"),scrollMarginX:z.spaceT(["scrollMarginLeft","scrollMarginRight"]),scrollMarginY:z.spaceT(["scrollMarginTop","scrollMarginBottom"]),scrollPadding:z.spaceT("scrollPadding"),scrollPaddingTop:z.spaceT("scrollPaddingTop"),scrollPaddingBottom:z.spaceT("scrollPaddingBottom"),scrollPaddingLeft:z.spaceT("scrollPaddingLeft"),scrollPaddingRight:z.spaceT("scrollPaddingRight"),scrollPaddingX:z.spaceT(["scrollPaddingLeft","scrollPaddingRight"]),scrollPaddingY:z.spaceT(["scrollPaddingTop","scrollPaddingBottom"])};function lD(e){return Io(e)&&e.reference?e.reference:String(e)}var Zv=(e,...t)=>t.map(lD).join(` ${e} `).replace(/calc/g,""),V6=(...e)=>`calc(${Zv("+",...e)})`,z6=(...e)=>`calc(${Zv("-",...e)})`,O2=(...e)=>`calc(${Zv("*",...e)})`,U6=(...e)=>`calc(${Zv("/",...e)})`,G6=e=>{const t=lD(e);return t!=null&&!Number.isNaN(parseFloat(t))?String(t).startsWith("-")?String(t).slice(1):`-${t}`:O2(t,-1)},Pa=Object.assign(e=>({add:(...t)=>Pa(V6(e,...t)),subtract:(...t)=>Pa(z6(e,...t)),multiply:(...t)=>Pa(O2(e,...t)),divide:(...t)=>Pa(U6(e,...t)),negate:()=>Pa(G6(e)),toString:()=>e.toString()}),{add:V6,subtract:z6,multiply:O2,divide:U6,negate:G6});function bme(e,t="-"){return e.replace(/\s+/g,t)}function Sme(e){const t=bme(e.toString());return wme(_me(t))}function _me(e){return e.includes("\\.")?e:!Number.isInteger(parseFloat(e.toString()))?e.replace(".","\\."):e}function wme(e){return e.replace(/[!-,/:-@[-^`{-~]/g,"\\$&")}function xme(e,t=""){return[t,e].filter(Boolean).join("-")}function Cme(e,t){return`var(${e}${t?`, ${t}`:""})`}function Tme(e,t=""){return Sme(`--${xme(e,t)}`)}function R2(e,t,n){const r=Tme(e,n);return{variable:r,reference:Cme(r,t)}}function g4e(e,t){const n={};for(const r of t){if(Array.isArray(r)){const[i,o]=r;n[i]=R2(`${e}-${i}`,o);continue}n[r]=R2(`${e}-${r}`)}return n}function Eme(e){const t=e==null?0:e.length;return t?e[t-1]:void 0}function Pme(e){const t=parseFloat(e.toString()),n=e.toString().replace(String(t),"");return{unitless:!n,value:t,unit:n}}function I2(e){if(e==null)return e;const{unitless:t}=Pme(e);return t||typeof e=="number"?`${e}px`:e}var uD=(e,t)=>parseInt(e[1],10)>parseInt(t[1],10)?1:-1,VC=e=>Object.fromEntries(Object.entries(e).sort(uD));function H6(e){const t=VC(e);return Object.assign(Object.values(t),t)}function Ame(e){const t=Object.keys(VC(e));return new Set(t)}function q6(e){var t;if(!e)return e;e=(t=I2(e))!=null?t:e;const n=-.02;return typeof e=="number"?`${e+n}`:e.replace(/(\d+\.?\d*)/u,r=>`${parseFloat(r)+n}`)}function pd(e,t){const n=["@media screen"];return e&&n.push("and",`(min-width: ${I2(e)})`),t&&n.push("and",`(max-width: ${I2(t)})`),n.join(" ")}function kme(e){var t;if(!e)return null;e.base=(t=e.base)!=null?t:"0px";const n=H6(e),r=Object.entries(e).sort(uD).map(([s,a],l,u)=>{var c;let[,d]=(c=u[l+1])!=null?c:[];return d=parseFloat(d)>0?q6(d):void 0,{_minW:q6(a),breakpoint:s,minW:a,maxW:d,maxWQuery:pd(null,d),minWQuery:pd(a),minMaxQuery:pd(a,d)}}),i=Ame(e),o=Array.from(i.values());return{keys:i,normalized:n,isResponsive(s){const a=Object.keys(s);return a.length>0&&a.every(l=>i.has(l))},asObject:VC(e),asArray:H6(e),details:r,get(s){return r.find(a=>a.breakpoint===s)},media:[null,...n.map(s=>pd(s)).slice(1)],toArrayValue(s){if(!Io(s))throw new Error("toArrayValue: value must be an object");const a=o.map(l=>{var u;return(u=s[l])!=null?u:null});for(;Eme(a)===null;)a.pop();return a},toObjectValue(s){if(!Array.isArray(s))throw new Error("toObjectValue: value must be an array");return s.reduce((a,l,u)=>{const c=o[u];return c!=null&&l!=null&&(a[c]=l),a},{})}}}var xn={hover:(e,t)=>`${e}:hover ${t}, ${e}[data-hover] ${t}`,focus:(e,t)=>`${e}:focus ${t}, ${e}[data-focus] ${t}`,focusVisible:(e,t)=>`${e}:focus-visible ${t}`,focusWithin:(e,t)=>`${e}:focus-within ${t}`,active:(e,t)=>`${e}:active ${t}, ${e}[data-active] ${t}`,disabled:(e,t)=>`${e}:disabled ${t}, ${e}[data-disabled] ${t}`,invalid:(e,t)=>`${e}:invalid ${t}, ${e}[data-invalid] ${t}`,checked:(e,t)=>`${e}:checked ${t}, ${e}[data-checked] ${t}`,indeterminate:(e,t)=>`${e}:indeterminate ${t}, ${e}[aria-checked=mixed] ${t}, ${e}[data-indeterminate] ${t}`,readOnly:(e,t)=>`${e}:read-only ${t}, ${e}[readonly] ${t}, ${e}[data-read-only] ${t}`,expanded:(e,t)=>`${e}:read-only ${t}, ${e}[aria-expanded=true] ${t}, ${e}[data-expanded] ${t}`,placeholderShown:(e,t)=>`${e}:placeholder-shown ${t}`},os=e=>cD(t=>e(t,"&"),"[role=group]","[data-group]",".group"),mo=e=>cD(t=>e(t,"~ &"),"[data-peer]",".peer"),cD=(e,...t)=>t.map(e).join(", "),Jv={_hover:"&:hover, &[data-hover]",_active:"&:active, &[data-active]",_focus:"&:focus, &[data-focus]",_highlighted:"&[data-highlighted]",_focusWithin:"&:focus-within",_focusVisible:"&:focus-visible, &[data-focus-visible]",_disabled:"&:disabled, &[disabled], &[aria-disabled=true], &[data-disabled]",_readOnly:"&[aria-readonly=true], &[readonly], &[data-readonly]",_before:"&::before",_after:"&::after",_empty:"&:empty",_expanded:"&[aria-expanded=true], &[data-expanded]",_checked:"&[aria-checked=true], &[data-checked]",_grabbed:"&[aria-grabbed=true], &[data-grabbed]",_pressed:"&[aria-pressed=true], &[data-pressed]",_invalid:"&[aria-invalid=true], &[data-invalid]",_valid:"&[data-valid], &[data-state=valid]",_loading:"&[data-loading], &[aria-busy=true]",_selected:"&[aria-selected=true], &[data-selected]",_hidden:"&[hidden], &[data-hidden]",_autofill:"&:-webkit-autofill",_even:"&:nth-of-type(even)",_odd:"&:nth-of-type(odd)",_first:"&:first-of-type",_firstLetter:"&::first-letter",_last:"&:last-of-type",_notFirst:"&:not(:first-of-type)",_notLast:"&:not(:last-of-type)",_visited:"&:visited",_activeLink:"&[aria-current=page]",_activeStep:"&[aria-current=step]",_indeterminate:"&:indeterminate, &[aria-checked=mixed], &[data-indeterminate]",_groupHover:os(xn.hover),_peerHover:mo(xn.hover),_groupFocus:os(xn.focus),_peerFocus:mo(xn.focus),_groupFocusVisible:os(xn.focusVisible),_peerFocusVisible:mo(xn.focusVisible),_groupActive:os(xn.active),_peerActive:mo(xn.active),_groupDisabled:os(xn.disabled),_peerDisabled:mo(xn.disabled),_groupInvalid:os(xn.invalid),_peerInvalid:mo(xn.invalid),_groupChecked:os(xn.checked),_peerChecked:mo(xn.checked),_groupFocusWithin:os(xn.focusWithin),_peerFocusWithin:mo(xn.focusWithin),_peerPlaceholderShown:mo(xn.placeholderShown),_placeholder:"&::placeholder",_placeholderShown:"&:placeholder-shown",_fullScreen:"&:fullscreen",_selection:"&::selection",_rtl:"[dir=rtl] &, &[dir=rtl]",_ltr:"[dir=ltr] &, &[dir=ltr]",_mediaDark:"@media (prefers-color-scheme: dark)",_mediaReduceMotion:"@media (prefers-reduced-motion: reduce)",_dark:".chakra-ui-dark &:not([data-theme]),[data-theme=dark] &:not([data-theme]),&[data-theme=dark]",_light:".chakra-ui-light &:not([data-theme]),[data-theme=light] &:not([data-theme]),&[data-theme=light]",_horizontal:"&[data-orientation=horizontal]",_vertical:"&[data-orientation=vertical]"},dD=Object.keys(Jv);function W6(e,t){return R2(String(e).replace(/\./g,"-"),void 0,t)}function Ome(e,t){let n={};const r={};for(const[i,o]of Object.entries(e)){const{isSemantic:s,value:a}=o,{variable:l,reference:u}=W6(i,t==null?void 0:t.cssVarPrefix);if(!s){if(i.startsWith("space")){const f=i.split("."),[h,...p]=f,m=`${h}.-${p.join(".")}`,S=Pa.negate(a),v=Pa.negate(u);r[m]={value:S,var:l,varRef:v}}n[l]=a,r[i]={value:a,var:l,varRef:u};continue}const c=f=>{const p=[String(i).split(".")[0],f].join(".");if(!e[p])return f;const{reference:S}=W6(p,t==null?void 0:t.cssVarPrefix);return S},d=Io(a)?a:{default:a};n=Wi(n,Object.entries(d).reduce((f,[h,p])=>{var m,S;if(!p)return f;const v=c(`${p}`);if(h==="default")return f[l]=v,f;const y=(S=(m=Jv)==null?void 0:m[h])!=null?S:h;return f[y]={[l]:v},f},{})),r[i]={value:u,var:l,varRef:u}}return{cssVars:n,cssMap:r}}function Rme(e,t=[]){const n=Object.assign({},e);for(const r of t)r in n&&delete n[r];return n}function Ime(e,t){const n={};for(const r of t)r in e&&(n[r]=e[r]);return n}function Mme(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}function K6(e,t,n={}){const{stop:r,getKey:i}=n;function o(s,a=[]){var l;if(Mme(s)||Array.isArray(s)){const u={};for(const[c,d]of Object.entries(s)){const f=(l=i==null?void 0:i(c))!=null?l:c,h=[...a,f];if(r!=null&&r(s,h))return t(s,a);u[f]=o(d,h)}return u}return t(s,a)}return o(e)}var Nme=["colors","borders","borderWidths","borderStyles","fonts","fontSizes","fontWeights","gradients","letterSpacings","lineHeights","radii","space","shadows","sizes","zIndices","transition","blur","breakpoints"];function Dme(e){return Ime(e,Nme)}function Lme(e){return e.semanticTokens}function $me(e){const{__cssMap:t,__cssVars:n,__breakpoints:r,...i}=e;return i}var Fme=e=>dD.includes(e)||e==="default";function Bme({tokens:e,semanticTokens:t}){const n={};return K6(e,(r,i)=>{r!=null&&(n[i.join(".")]={isSemantic:!1,value:r})}),K6(t,(r,i)=>{r!=null&&(n[i.join(".")]={isSemantic:!0,value:r})},{stop:r=>Object.keys(r).every(Fme)}),n}function m4e(e){var t;const n=$me(e),r=Dme(n),i=Lme(n),o=Bme({tokens:r,semanticTokens:i}),s=(t=n.config)==null?void 0:t.cssVarPrefix,{cssMap:a,cssVars:l}=Ome(o,{cssVarPrefix:s});return Object.assign(n,{__cssVars:{...{"--chakra-ring-inset":"var(--chakra-empty,/*!*/ /*!*/)","--chakra-ring-offset-width":"0px","--chakra-ring-offset-color":"#fff","--chakra-ring-color":"rgba(66, 153, 225, 0.6)","--chakra-ring-offset-shadow":"0 0 #0000","--chakra-ring-shadow":"0 0 #0000","--chakra-space-x-reverse":"0","--chakra-space-y-reverse":"0"},...l},__cssMap:a,__breakpoints:kme(n.breakpoints)}),n}var zC=Wi({},Cg,Ue,rme,ny,zr,ime,hme,ome,aD,fme,Od,k2,dt,vme,yme,pme,gme,sme,mme),jme=Object.assign({},dt,zr,ny,aD,Od),y4e=Object.keys(jme),Vme=[...Object.keys(zC),...dD],zme={...zC,...Jv},Ume=e=>e in zme,Gme=e=>t=>{if(!t.__breakpoints)return e;const{isResponsive:n,toArrayValue:r,media:i}=t.__breakpoints,o={};for(const s in e){let a=Na(e[s],t);if(a==null)continue;if(a=Io(a)&&n(a)?r(a):a,!Array.isArray(a)){o[s]=a;continue}const l=a.slice(0,i.length).length;for(let u=0;ue.startsWith("--")&&typeof t=="string"&&!qme(t),Kme=(e,t)=>{var n,r;if(t==null)return t;const i=l=>{var u,c;return(c=(u=e.__cssMap)==null?void 0:u[l])==null?void 0:c.varRef},o=l=>{var u;return(u=i(l))!=null?u:l},[s,a]=Hme(t);return t=(r=(n=i(s))!=null?n:o(a))!=null?r:o(t),t};function Xme(e){const{configs:t={},pseudos:n={},theme:r}=e,i=(o,s=!1)=>{var a,l,u;const c=Na(o,r),d=Gme(c)(r);let f={};for(let h in d){const p=d[h];let m=Na(p,r);h in n&&(h=n[h]),Wme(h,m)&&(m=Kme(r,m));let S=t[h];if(S===!0&&(S={property:h}),Io(m)){f[h]=(a=f[h])!=null?a:{},f[h]=Wi({},f[h],i(m,!0));continue}let v=(u=(l=S==null?void 0:S.transform)==null?void 0:l.call(S,m,r,c))!=null?u:m;v=S!=null&&S.processResult?i(v,!0):v;const y=Na(S==null?void 0:S.property,r);if(!s&&(S!=null&&S.static)){const g=Na(S.static,r);f=Wi({},f,g)}if(y&&Array.isArray(y)){for(const g of y)f[g]=v;continue}if(y){y==="&"&&Io(v)?f=Wi({},f,v):f[y]=v;continue}if(Io(v)){f=Wi({},f,v);continue}f[h]=v}return f};return i}var Yme=e=>t=>Xme({theme:t,pseudos:Jv,configs:zC})(e);function v4e(e){return e}function b4e(e){return e}function S4e(e){return{definePartsStyle(t){return t},defineMultiStyleConfig(t){return{parts:e,...t}}}}function Qme(e,t){if(Array.isArray(e))return e;if(Io(e))return t(e);if(e!=null)return[e]}function Zme(e,t){for(let n=t+1;n{Wi(u,{[g]:f?y[g]:{[v]:y[g]}})});continue}if(!h){f?Wi(u,y):u[v]=y;continue}u[v]=y}}return u}}function eye(e){return t=>{var n;const{variant:r,size:i,theme:o}=t,s=Jme(o);return Wi({},Na((n=e.baseStyle)!=null?n:{},t),s(e,"sizes",i,t),s(e,"variants",r,t))}}function _4e(e,t,n){var r,i,o;return(o=(i=(r=e.__cssMap)==null?void 0:r[`${t}.${n}`])==null?void 0:i.varRef)!=null?o:n}function fD(e){return Rme(e,["styleConfig","size","variant","colorScheme"])}function tye(e){return e!=null&&typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.ELEMENT_NODE}function w4e(e){var t;return tye(e)&&(t=e.ownerDocument)!=null?t:document}function nye(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var rye=nye();function iye(e,t){const n={};return Object.keys(e).forEach(r=>{t.includes(r)||(n[r]=e[r])}),n}function oye(e,t,n,r){const i=typeof t=="string"?t.split("."):[t];for(r=0;r{const t=new WeakMap;return(r,i,o,s)=>{if(typeof r>"u")return e(r,i,o);t.has(r)||t.set(r,new Map);const a=t.get(r);if(a.has(i))return a.get(i);const l=e(r,i,o,s);return a.set(i,l),l}},aye=sye(oye);function hD(e,t){const n={};return Object.keys(e).forEach(r=>{const i=e[r];t(i,r,e)&&(n[r]=i)}),n}var pD=e=>hD(e,t=>t!=null);function lye(e){return typeof e=="function"}function uye(e,...t){return lye(e)?e(...t):e}function cye(...e){return function(n){e.some(r=>(r==null||r(n),n==null?void 0:n.defaultPrevented))}}var dye=typeof Element<"u",fye=typeof Map=="function",hye=typeof Set=="function",pye=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function Tg(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var n,r,i;if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!Tg(e[r],t[r]))return!1;return!0}var o;if(fye&&e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(o=e.entries();!(r=o.next()).done;)if(!t.has(r.value[0]))return!1;for(o=e.entries();!(r=o.next()).done;)if(!Tg(r.value[1],t.get(r.value[0])))return!1;return!0}if(hye&&e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(o=e.entries();!(r=o.next()).done;)if(!t.has(r.value[0]))return!1;return!0}if(pye&&ArrayBuffer.isView(e)&&ArrayBuffer.isView(t)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(e[r]!==t[r])return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf&&typeof e.valueOf=="function"&&typeof t.valueOf=="function")return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString&&typeof e.toString=="function"&&typeof t.toString=="function")return e.toString()===t.toString();if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!Object.prototype.hasOwnProperty.call(t,i[r]))return!1;if(dye&&e instanceof Element)return!1;for(r=n;r--!==0;)if(!((i[r]==="_owner"||i[r]==="__v"||i[r]==="__o")&&e.$$typeof)&&!Tg(e[i[r]],t[i[r]]))return!1;return!0}return e!==e&&t!==t}var gye=function(t,n){try{return Tg(t,n)}catch(r){if((r.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw r}};const mye=al(gye);function gD(e,t={}){var n;const{styleConfig:r,...i}=t,{theme:o,colorMode:s}=Nge(),a=e?aye(o,`components.${e}`):void 0,l=r||a,u=Wi({theme:o,colorMode:s},(n=l==null?void 0:l.defaultProps)!=null?n:{},pD(iye(i,["children"]))),c=k.useRef({});if(l){const f=eye(l)(u);mye(c.current,f)||(c.current=f)}return c.current}function mD(e,t={}){return gD(e,t)}function x4e(e,t={}){return gD(e,t)}var yye=new Set([...Vme,"textStyle","layerStyle","apply","noOfLines","focusBorderColor","errorBorderColor","as","__css","css","sx"]),vye=new Set(["htmlWidth","htmlHeight","htmlSize","htmlTranslate"]);function bye(e){return vye.has(e)||!yye.has(e)}function Sye(e,...t){if(e==null)throw new TypeError("Cannot convert undefined or null to object");const n={...e};for(const r of t)if(r!=null)for(const i in r)Object.prototype.hasOwnProperty.call(r,i)&&(i in n&&delete n[i],n[i]=r[i]);return n}var _ye=/^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|suppressHydrationWarning|valueLink|abbr|accept|acceptCharset|accessKey|action|allow|allowUserMedia|allowPaymentRequest|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|decoding|default|defer|dir|disabled|disablePictureInPicture|download|draggable|encType|enterKeyHint|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loading|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|translate|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|incremental|fallback|inert|itemProp|itemScope|itemType|itemID|itemRef|on|option|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class|autofocus)|(([Dd][Aa][Tt][Aa]|[Aa][Rr][Ii][Aa]|x)-.*))$/,wye=XN(function(e){return _ye.test(e)||e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)<91}),xye=wye,Cye=function(t){return t!=="theme"},X6=function(t){return typeof t=="string"&&t.charCodeAt(0)>96?xye:Cye},Y6=function(t,n,r){var i;if(n){var o=n.shouldForwardProp;i=t.__emotion_forwardProp&&o?function(s){return t.__emotion_forwardProp(s)&&o(s)}:o}return typeof i!="function"&&r&&(i=t.__emotion_forwardProp),i},Tye=function(t){var n=t.cache,r=t.serialized,i=t.isStringTag;return QN(n,r,i),Age(function(){return ZN(n,r,i)}),null},Eye=function e(t,n){var r=t.__emotion_real===t,i=r&&t.__emotion_base||t,o,s;n!==void 0&&(o=n.label,s=n.target);var a=Y6(t,n,r),l=a||X6(i),u=!l("as");return function(){var c=arguments,d=r&&t.__emotion_styles!==void 0?t.__emotion_styles.slice(0):[];if(o!==void 0&&d.push("label:"+o+";"),c[0]==null||c[0].raw===void 0)d.push.apply(d,c);else{d.push(c[0][0]);for(var f=c.length,h=1;ht=>{const{theme:n,css:r,__css:i,sx:o,...s}=t,a=hD(s,(d,f)=>Ume(f)),l=uye(e,t),u=Sye({},i,l,pD(a),o),c=Yme(u)(t.theme);return r?[c,r]:c};function tS(e,t){const{baseStyle:n,...r}=t??{};r.shouldForwardProp||(r.shouldForwardProp=bye);const i=kye({baseStyle:n}),o=Aye(e,r)(i);return We.forwardRef(function(l,u){const{colorMode:c,forced:d}=BC();return We.createElement(o,{ref:u,"data-theme":d?c:void 0,...l})})}function Oye(){const e=new Map;return new Proxy(tS,{apply(t,n,r){return tS(...r)},get(t,n){return e.has(n)||e.set(n,tS(n)),e.get(n)}})}var sl=Oye();function Tl(e){return k.forwardRef(e)}const yD=k.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"}),e1=k.createContext({}),Lh=k.createContext(null),t1=typeof document<"u",iy=t1?k.useLayoutEffect:k.useEffect,vD=k.createContext({strict:!1});function Rye(e,t,n,r){const{visualElement:i}=k.useContext(e1),o=k.useContext(vD),s=k.useContext(Lh),a=k.useContext(yD).reducedMotion,l=k.useRef();r=r||o.renderer,!l.current&&r&&(l.current=r(e,{visualState:t,parent:i,props:n,presenceContext:s,blockInitialAnimation:s?s.initial===!1:!1,reducedMotionConfig:a}));const u=l.current;return k.useInsertionEffect(()=>{u&&u.update(n,s)}),iy(()=>{u&&u.render()}),k.useEffect(()=>{u&&u.updateFeatures()}),(window.HandoffAppearAnimations?iy:k.useEffect)(()=>{u&&u.animationState&&u.animationState.animateChanges()}),u}function hu(e){return typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function Iye(e,t,n){return k.useCallback(r=>{r&&e.mount&&e.mount(r),t&&(r?t.mount(r):t.unmount()),n&&(typeof n=="function"?n(r):hu(n)&&(n.current=r))},[t])}function Gf(e){return typeof e=="string"||Array.isArray(e)}function n1(e){return typeof e=="object"&&typeof e.start=="function"}const UC=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],GC=["initial",...UC];function r1(e){return n1(e.animate)||GC.some(t=>Gf(e[t]))}function bD(e){return!!(r1(e)||e.variants)}function Mye(e,t){if(r1(e)){const{initial:n,animate:r}=e;return{initial:n===!1||Gf(n)?n:void 0,animate:Gf(r)?r:void 0}}return e.inherit!==!1?t:{}}function Nye(e){const{initial:t,animate:n}=Mye(e,k.useContext(e1));return k.useMemo(()=>({initial:t,animate:n}),[Z6(t),Z6(n)])}function Z6(e){return Array.isArray(e)?e.join(" "):e}const J6={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},Hf={};for(const e in J6)Hf[e]={isEnabled:t=>J6[e].some(n=>!!t[n])};function Dye(e){for(const t in e)Hf[t]={...Hf[t],...e[t]}}const HC=k.createContext({}),SD=k.createContext({}),Lye=Symbol.for("motionComponentSymbol");function $ye({preloadedFeatures:e,createVisualElement:t,useRender:n,useVisualState:r,Component:i}){e&&Dye(e);function o(a,l){let u;const c={...k.useContext(yD),...a,layoutId:Fye(a)},{isStatic:d}=c,f=Nye(a),h=r(a,d);if(!d&&t1){f.visualElement=Rye(i,h,c,t);const p=k.useContext(SD),m=k.useContext(vD).strict;f.visualElement&&(u=f.visualElement.loadFeatures(c,m,e,p))}return k.createElement(e1.Provider,{value:f},u&&f.visualElement?k.createElement(u,{visualElement:f.visualElement,...c}):null,n(i,a,Iye(h,f.visualElement,l),h,d,f.visualElement))}const s=k.forwardRef(o);return s[Lye]=i,s}function Fye({layoutId:e}){const t=k.useContext(HC).id;return t&&e!==void 0?t+"-"+e:e}function Bye(e){function t(r,i={}){return $ye(e(r,i))}if(typeof Proxy>"u")return t;const n=new Map;return new Proxy(t,{get:(r,i)=>(n.has(i)||n.set(i,t(i)),n.get(i))})}const jye=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function qC(e){return typeof e!="string"||e.includes("-")?!1:!!(jye.indexOf(e)>-1||/[A-Z]/.test(e))}const oy={};function Vye(e){Object.assign(oy,e)}const $h=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],El=new Set($h);function _D(e,{layout:t,layoutId:n}){return El.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!oy[e]||e==="opacity")}const _r=e=>!!(e&&e.getVelocity),zye={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Uye=$h.length;function Gye(e,{enableHardwareAcceleration:t=!0,allowTransformNone:n=!0},r,i){let o="";for(let s=0;st=>typeof t=="string"&&t.startsWith(e),xD=wD("--"),M2=wD("var(--"),Hye=/var\s*\(\s*--[\w-]+(\s*,\s*(?:(?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)+)?\s*\)/g,qye=(e,t)=>t&&typeof e=="number"?t.transform(e):e,Ks=(e,t,n)=>Math.min(Math.max(n,e),t),Pl={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},Rd={...Pl,transform:e=>Ks(0,1,e)},Up={...Pl,default:1},Id=e=>Math.round(e*1e5)/1e5,i1=/(-)?([\d]*\.?[\d])+/g,CD=/(#[0-9a-f]{3,8}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))/gi,Wye=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))$/i;function Fh(e){return typeof e=="string"}const Bh=e=>({test:t=>Fh(t)&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),as=Bh("deg"),Ji=Bh("%"),me=Bh("px"),Kye=Bh("vh"),Xye=Bh("vw"),eP={...Ji,parse:e=>Ji.parse(e)/100,transform:e=>Ji.transform(e*100)},tP={...Pl,transform:Math.round},TD={borderWidth:me,borderTopWidth:me,borderRightWidth:me,borderBottomWidth:me,borderLeftWidth:me,borderRadius:me,radius:me,borderTopLeftRadius:me,borderTopRightRadius:me,borderBottomRightRadius:me,borderBottomLeftRadius:me,width:me,maxWidth:me,height:me,maxHeight:me,size:me,top:me,right:me,bottom:me,left:me,padding:me,paddingTop:me,paddingRight:me,paddingBottom:me,paddingLeft:me,margin:me,marginTop:me,marginRight:me,marginBottom:me,marginLeft:me,rotate:as,rotateX:as,rotateY:as,rotateZ:as,scale:Up,scaleX:Up,scaleY:Up,scaleZ:Up,skew:as,skewX:as,skewY:as,distance:me,translateX:me,translateY:me,translateZ:me,x:me,y:me,z:me,perspective:me,transformPerspective:me,opacity:Rd,originX:eP,originY:eP,originZ:me,zIndex:tP,fillOpacity:Rd,strokeOpacity:Rd,numOctaves:tP};function WC(e,t,n,r){const{style:i,vars:o,transform:s,transformOrigin:a}=e;let l=!1,u=!1,c=!0;for(const d in t){const f=t[d];if(xD(d)){o[d]=f;continue}const h=TD[d],p=qye(f,h);if(El.has(d)){if(l=!0,s[d]=p,!c)continue;f!==(h.default||0)&&(c=!1)}else d.startsWith("origin")?(u=!0,a[d]=p):i[d]=p}if(t.transform||(l||r?i.transform=Gye(e.transform,n,c,r):i.transform&&(i.transform="none")),u){const{originX:d="50%",originY:f="50%",originZ:h=0}=a;i.transformOrigin=`${d} ${f} ${h}`}}const KC=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function ED(e,t,n){for(const r in t)!_r(t[r])&&!_D(r,n)&&(e[r]=t[r])}function Yye({transformTemplate:e},t,n){return k.useMemo(()=>{const r=KC();return WC(r,t,{enableHardwareAcceleration:!n},e),Object.assign({},r.vars,r.style)},[t])}function Qye(e,t,n){const r=e.style||{},i={};return ED(i,r,e),Object.assign(i,Yye(e,t,n)),e.transformValues?e.transformValues(i):i}function Zye(e,t,n){const r={},i=Qye(e,t,n);return e.drag&&e.dragListener!==!1&&(r.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(r.tabIndex=0),r.style=i,r}const Jye=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","transformValues","custom","inherit","onLayoutAnimationStart","onLayoutAnimationComplete","onLayoutMeasure","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","ignoreStrict","viewport"]);function sy(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||Jye.has(e)}let PD=e=>!sy(e);function e0e(e){e&&(PD=t=>t.startsWith("on")?!sy(t):e(t))}try{e0e(require("@emotion/is-prop-valid").default)}catch{}function t0e(e,t,n){const r={};for(const i in e)i==="values"&&typeof e.values=="object"||(PD(i)||n===!0&&sy(i)||!t&&!sy(i)||e.draggable&&i.startsWith("onDrag"))&&(r[i]=e[i]);return r}function nP(e,t,n){return typeof e=="string"?e:me.transform(t+n*e)}function n0e(e,t,n){const r=nP(t,e.x,e.width),i=nP(n,e.y,e.height);return`${r} ${i}`}const r0e={offset:"stroke-dashoffset",array:"stroke-dasharray"},i0e={offset:"strokeDashoffset",array:"strokeDasharray"};function o0e(e,t,n=1,r=0,i=!0){e.pathLength=1;const o=i?r0e:i0e;e[o.offset]=me.transform(-r);const s=me.transform(t),a=me.transform(n);e[o.array]=`${s} ${a}`}function XC(e,{attrX:t,attrY:n,attrScale:r,originX:i,originY:o,pathLength:s,pathSpacing:a=1,pathOffset:l=0,...u},c,d,f){if(WC(e,u,c,f),d){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:h,style:p,dimensions:m}=e;h.transform&&(m&&(p.transform=h.transform),delete h.transform),m&&(i!==void 0||o!==void 0||p.transform)&&(p.transformOrigin=n0e(m,i!==void 0?i:.5,o!==void 0?o:.5)),t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),r!==void 0&&(h.scale=r),s!==void 0&&o0e(h,s,a,l,!1)}const AD=()=>({...KC(),attrs:{}}),YC=e=>typeof e=="string"&&e.toLowerCase()==="svg";function s0e(e,t,n,r){const i=k.useMemo(()=>{const o=AD();return XC(o,t,{enableHardwareAcceleration:!1},YC(r),e.transformTemplate),{...o.attrs,style:{...o.style}}},[t]);if(e.style){const o={};ED(o,e.style,e),i.style={...o,...i.style}}return i}function a0e(e=!1){return(n,r,i,{latestValues:o},s)=>{const l=(qC(n)?s0e:Zye)(r,o,s,n),c={...t0e(r,typeof n=="string",e),...l,ref:i},{children:d}=r,f=k.useMemo(()=>_r(d)?d.get():d,[d]);return k.createElement(n,{...c,children:f})}}const QC=e=>e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();function kD(e,{style:t,vars:n},r,i){Object.assign(e.style,t,i&&i.getProjectionStyles(r));for(const o in n)e.style.setProperty(o,n[o])}const OD=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function RD(e,t,n,r){kD(e,t,void 0,r);for(const i in t.attrs)e.setAttribute(OD.has(i)?i:QC(i),t.attrs[i])}function ZC(e,t){const{style:n}=e,r={};for(const i in n)(_r(n[i])||t.style&&_r(t.style[i])||_D(i,e))&&(r[i]=n[i]);return r}function ID(e,t){const n=ZC(e,t);for(const r in e)if(_r(e[r])||_r(t[r])){const i=$h.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;n[i]=e[r]}return n}function JC(e,t,n,r={},i={}){return typeof t=="function"&&(t=t(n!==void 0?n:e.custom,r,i)),typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"&&(t=t(n!==void 0?n:e.custom,r,i)),t}function MD(e){const t=k.useRef(null);return t.current===null&&(t.current=e()),t.current}const ay=e=>Array.isArray(e),l0e=e=>!!(e&&typeof e=="object"&&e.mix&&e.toValue),u0e=e=>ay(e)?e[e.length-1]||0:e;function Eg(e){const t=_r(e)?e.get():e;return l0e(t)?t.toValue():t}function c0e({scrapeMotionValuesFromProps:e,createRenderState:t,onMount:n},r,i,o){const s={latestValues:d0e(r,i,o,e),renderState:t()};return n&&(s.mount=a=>n(r,a,s)),s}const ND=e=>(t,n)=>{const r=k.useContext(e1),i=k.useContext(Lh),o=()=>c0e(e,t,r,i);return n?o():MD(o)};function d0e(e,t,n,r){const i={},o=r(e,{});for(const f in o)i[f]=Eg(o[f]);let{initial:s,animate:a}=e;const l=r1(e),u=bD(e);t&&u&&!l&&e.inherit!==!1&&(s===void 0&&(s=t.initial),a===void 0&&(a=t.animate));let c=n?n.initial===!1:!1;c=c||s===!1;const d=c?a:s;return d&&typeof d!="boolean"&&!n1(d)&&(Array.isArray(d)?d:[d]).forEach(h=>{const p=JC(e,h);if(!p)return;const{transitionEnd:m,transition:S,...v}=p;for(const y in v){let g=v[y];if(Array.isArray(g)){const b=c?g.length-1:0;g=g[b]}g!==null&&(i[y]=g)}for(const y in m)i[y]=m[y]}),i}const f0e={useVisualState:ND({scrapeMotionValuesFromProps:ID,createRenderState:AD,onMount:(e,t,{renderState:n,latestValues:r})=>{try{n.dimensions=typeof t.getBBox=="function"?t.getBBox():t.getBoundingClientRect()}catch{n.dimensions={x:0,y:0,width:0,height:0}}XC(n,r,{enableHardwareAcceleration:!1},YC(t.tagName),e.transformTemplate),RD(t,n)}})},h0e={useVisualState:ND({scrapeMotionValuesFromProps:ZC,createRenderState:KC})};function p0e(e,{forwardMotionProps:t=!1},n,r){return{...qC(e)?f0e:h0e,preloadedFeatures:n,useRender:a0e(t),createVisualElement:r,Component:e}}function Ao(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}const DD=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1;function o1(e,t="page"){return{point:{x:e[t+"X"],y:e[t+"Y"]}}}const g0e=e=>t=>DD(t)&&e(t,o1(t));function Mo(e,t,n,r){return Ao(e,t,g0e(n),r)}const m0e=(e,t)=>n=>t(e(n)),Ns=(...e)=>e.reduce(m0e);function LD(e){let t=null;return()=>{const n=()=>{t=null};return t===null?(t=e,n):!1}}const rP=LD("dragHorizontal"),iP=LD("dragVertical");function $D(e){let t=!1;if(e==="y")t=iP();else if(e==="x")t=rP();else{const n=rP(),r=iP();n&&r?t=()=>{n(),r()}:(n&&n(),r&&r())}return t}function FD(){const e=$D(!0);return e?(e(),!1):!0}class ua{constructor(t){this.isMounted=!1,this.node=t}update(){}}const Qt=e=>e;function y0e(e){let t=[],n=[],r=0,i=!1,o=!1;const s=new WeakSet,a={schedule:(l,u=!1,c=!1)=>{const d=c&&i,f=d?t:n;return u&&s.add(l),f.indexOf(l)===-1&&(f.push(l),d&&i&&(r=t.length)),l},cancel:l=>{const u=n.indexOf(l);u!==-1&&n.splice(u,1),s.delete(l)},process:l=>{if(i){o=!0;return}if(i=!0,[t,n]=[n,t],n.length=0,r=t.length,r)for(let u=0;u(d[f]=y0e(()=>n=!0),d),{}),s=d=>o[d].process(i),a=d=>{n=!1,i.delta=r?1e3/60:Math.max(Math.min(d-i.timestamp,v0e),1),i.timestamp=d,i.isProcessing=!0,Gp.forEach(s),i.isProcessing=!1,n&&t&&(r=!1,e(a))},l=()=>{n=!0,r=!0,i.isProcessing||e(a)};return{schedule:Gp.reduce((d,f)=>{const h=o[f];return d[f]=(p,m=!1,S=!1)=>(n||l(),h.schedule(p,m,S)),d},{}),cancel:d=>Gp.forEach(f=>o[f].cancel(d)),state:i,steps:o}}const{schedule:_t,cancel:Uo,state:$n,steps:nS}=b0e(typeof requestAnimationFrame<"u"?requestAnimationFrame:Qt,!0);function oP(e,t){const n="pointer"+(t?"enter":"leave"),r="onHover"+(t?"Start":"End"),i=(o,s)=>{if(o.type==="touch"||FD())return;const a=e.getProps();e.animationState&&a.whileHover&&e.animationState.setActive("whileHover",t),a[r]&&_t.update(()=>a[r](o,s))};return Mo(e.current,n,i,{passive:!e.getProps()[r]})}class S0e extends ua{mount(){this.unmount=Ns(oP(this.node,!0),oP(this.node,!1))}unmount(){}}class _0e extends ua{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Ns(Ao(this.node.current,"focus",()=>this.onFocus()),Ao(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}const BD=(e,t)=>t?e===t?!0:BD(e,t.parentElement):!1;function rS(e,t){if(!t)return;const n=new PointerEvent("pointer"+e);t(n,o1(n))}class w0e extends ua{constructor(){super(...arguments),this.removeStartListeners=Qt,this.removeEndListeners=Qt,this.removeAccessibleListeners=Qt,this.startPointerPress=(t,n)=>{if(this.removeEndListeners(),this.isPressing)return;const r=this.node.getProps(),o=Mo(window,"pointerup",(a,l)=>{if(!this.checkPressEnd())return;const{onTap:u,onTapCancel:c}=this.node.getProps();_t.update(()=>{BD(this.node.current,a.target)?u&&u(a,l):c&&c(a,l)})},{passive:!(r.onTap||r.onPointerUp)}),s=Mo(window,"pointercancel",(a,l)=>this.cancelPress(a,l),{passive:!(r.onTapCancel||r.onPointerCancel)});this.removeEndListeners=Ns(o,s),this.startPress(t,n)},this.startAccessiblePress=()=>{const t=o=>{if(o.key!=="Enter"||this.isPressing)return;const s=a=>{a.key!=="Enter"||!this.checkPressEnd()||rS("up",(l,u)=>{const{onTap:c}=this.node.getProps();c&&_t.update(()=>c(l,u))})};this.removeEndListeners(),this.removeEndListeners=Ao(this.node.current,"keyup",s),rS("down",(a,l)=>{this.startPress(a,l)})},n=Ao(this.node.current,"keydown",t),r=()=>{this.isPressing&&rS("cancel",(o,s)=>this.cancelPress(o,s))},i=Ao(this.node.current,"blur",r);this.removeAccessibleListeners=Ns(n,i)}}startPress(t,n){this.isPressing=!0;const{onTapStart:r,whileTap:i}=this.node.getProps();i&&this.node.animationState&&this.node.animationState.setActive("whileTap",!0),r&&_t.update(()=>r(t,n))}checkPressEnd(){return this.removeEndListeners(),this.isPressing=!1,this.node.getProps().whileTap&&this.node.animationState&&this.node.animationState.setActive("whileTap",!1),!FD()}cancelPress(t,n){if(!this.checkPressEnd())return;const{onTapCancel:r}=this.node.getProps();r&&_t.update(()=>r(t,n))}mount(){const t=this.node.getProps(),n=Mo(this.node.current,"pointerdown",this.startPointerPress,{passive:!(t.onTapStart||t.onPointerStart)}),r=Ao(this.node.current,"focus",this.startAccessiblePress);this.removeStartListeners=Ns(n,r)}unmount(){this.removeStartListeners(),this.removeEndListeners(),this.removeAccessibleListeners()}}const N2=new WeakMap,iS=new WeakMap,x0e=e=>{const t=N2.get(e.target);t&&t(e)},C0e=e=>{e.forEach(x0e)};function T0e({root:e,...t}){const n=e||document;iS.has(n)||iS.set(n,{});const r=iS.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(C0e,{root:e,...t})),r[i]}function E0e(e,t,n){const r=T0e(t);return N2.set(e,n),r.observe(e),()=>{N2.delete(e),r.unobserve(e)}}const P0e={some:0,all:1};class A0e extends ua{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:r,amount:i="some",once:o}=t,s={root:n?n.current:void 0,rootMargin:r,threshold:typeof i=="number"?i:P0e[i]},a=l=>{const{isIntersecting:u}=l;if(this.isInView===u||(this.isInView=u,o&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:c,onViewportLeave:d}=this.node.getProps(),f=u?c:d;f&&f(l)};return E0e(this.node.current,s,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(k0e(t,n))&&this.startObserver()}unmount(){}}function k0e({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const O0e={inView:{Feature:A0e},tap:{Feature:w0e},focus:{Feature:_0e},hover:{Feature:S0e}};function jD(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let r=0;rt[r]=n.get()),t}function I0e(e){const t={};return e.values.forEach((n,r)=>t[r]=n.getVelocity()),t}function s1(e,t,n){const r=e.getProps();return JC(r,t,n!==void 0?n:r.custom,R0e(e),I0e(e))}const M0e="framerAppearId",N0e="data-"+QC(M0e);let D0e=Qt,e3=Qt;const Ds=e=>e*1e3,No=e=>e/1e3,L0e={current:!1},VD=e=>Array.isArray(e)&&typeof e[0]=="number";function zD(e){return!!(!e||typeof e=="string"&&UD[e]||VD(e)||Array.isArray(e)&&e.every(zD))}const gd=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,UD={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:gd([0,.65,.55,1]),circOut:gd([.55,0,1,.45]),backIn:gd([.31,.01,.66,-.59]),backOut:gd([.33,1.53,.69,.99])};function GD(e){if(e)return VD(e)?gd(e):Array.isArray(e)?e.map(GD):UD[e]}function $0e(e,t,n,{delay:r=0,duration:i,repeat:o=0,repeatType:s="loop",ease:a,times:l}={}){const u={[t]:n};l&&(u.offset=l);const c=GD(a);return Array.isArray(c)&&(u.easing=c),e.animate(u,{delay:r,duration:i,easing:Array.isArray(c)?"linear":c,fill:"both",iterations:o+1,direction:s==="reverse"?"alternate":"normal"})}const sP={waapi:()=>Object.hasOwnProperty.call(Element.prototype,"animate")},oS={},HD={};for(const e in sP)HD[e]=()=>(oS[e]===void 0&&(oS[e]=sP[e]()),oS[e]);function F0e(e,{repeat:t,repeatType:n="loop"}){const r=t&&n!=="loop"&&t%2===1?0:e.length-1;return e[r]}const qD=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,B0e=1e-7,j0e=12;function V0e(e,t,n,r,i){let o,s,a=0;do s=t+(n-t)/2,o=qD(s,r,i)-e,o>0?n=s:t=s;while(Math.abs(o)>B0e&&++aV0e(o,0,1,e,n);return o=>o===0||o===1?o:qD(i(o),t,r)}const z0e=jh(.42,0,1,1),U0e=jh(0,0,.58,1),WD=jh(.42,0,.58,1),G0e=e=>Array.isArray(e)&&typeof e[0]!="number",KD=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,XD=e=>t=>1-e(1-t),YD=e=>1-Math.sin(Math.acos(e)),t3=XD(YD),H0e=KD(t3),QD=jh(.33,1.53,.69,.99),n3=XD(QD),q0e=KD(n3),W0e=e=>(e*=2)<1?.5*n3(e):.5*(2-Math.pow(2,-10*(e-1))),K0e={linear:Qt,easeIn:z0e,easeInOut:WD,easeOut:U0e,circIn:YD,circInOut:H0e,circOut:t3,backIn:n3,backInOut:q0e,backOut:QD,anticipate:W0e},aP=e=>{if(Array.isArray(e)){e3(e.length===4);const[t,n,r,i]=e;return jh(t,n,r,i)}else if(typeof e=="string")return K0e[e];return e},r3=(e,t)=>n=>!!(Fh(n)&&Wye.test(n)&&n.startsWith(e)||t&&Object.prototype.hasOwnProperty.call(n,t)),ZD=(e,t,n)=>r=>{if(!Fh(r))return r;const[i,o,s,a]=r.match(i1);return{[e]:parseFloat(i),[t]:parseFloat(o),[n]:parseFloat(s),alpha:a!==void 0?parseFloat(a):1}},X0e=e=>Ks(0,255,e),sS={...Pl,transform:e=>Math.round(X0e(e))},Da={test:r3("rgb","red"),parse:ZD("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:r=1})=>"rgba("+sS.transform(e)+", "+sS.transform(t)+", "+sS.transform(n)+", "+Id(Rd.transform(r))+")"};function Y0e(e){let t="",n="",r="",i="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),r=e.substring(5,7),i=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),r=e.substring(3,4),i=e.substring(4,5),t+=t,n+=n,r+=r,i+=i),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:i?parseInt(i,16)/255:1}}const D2={test:r3("#"),parse:Y0e,transform:Da.transform},pu={test:r3("hsl","hue"),parse:ZD("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(e)+", "+Ji.transform(Id(t))+", "+Ji.transform(Id(n))+", "+Id(Rd.transform(r))+")"},Xn={test:e=>Da.test(e)||D2.test(e)||pu.test(e),parse:e=>Da.test(e)?Da.parse(e):pu.test(e)?pu.parse(e):D2.parse(e),transform:e=>Fh(e)?e:e.hasOwnProperty("red")?Da.transform(e):pu.transform(e)},At=(e,t,n)=>-n*e+n*t+e;function aS(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function Q0e({hue:e,saturation:t,lightness:n,alpha:r}){e/=360,t/=100,n/=100;let i=0,o=0,s=0;if(!t)i=o=s=n;else{const a=n<.5?n*(1+t):n+t-n*t,l=2*n-a;i=aS(l,a,e+1/3),o=aS(l,a,e),s=aS(l,a,e-1/3)}return{red:Math.round(i*255),green:Math.round(o*255),blue:Math.round(s*255),alpha:r}}const lS=(e,t,n)=>{const r=e*e;return Math.sqrt(Math.max(0,n*(t*t-r)+r))},Z0e=[D2,Da,pu],J0e=e=>Z0e.find(t=>t.test(e));function lP(e){const t=J0e(e);let n=t.parse(e);return t===pu&&(n=Q0e(n)),n}const JD=(e,t)=>{const n=lP(e),r=lP(t),i={...n};return o=>(i.red=lS(n.red,r.red,o),i.green=lS(n.green,r.green,o),i.blue=lS(n.blue,r.blue,o),i.alpha=At(n.alpha,r.alpha,o),Da.transform(i))};function eve(e){var t,n;return isNaN(e)&&Fh(e)&&(((t=e.match(i1))===null||t===void 0?void 0:t.length)||0)+(((n=e.match(CD))===null||n===void 0?void 0:n.length)||0)>0}const eL={regex:Hye,countKey:"Vars",token:"${v}",parse:Qt},tL={regex:CD,countKey:"Colors",token:"${c}",parse:Xn.parse},nL={regex:i1,countKey:"Numbers",token:"${n}",parse:Pl.parse};function uS(e,{regex:t,countKey:n,token:r,parse:i}){const o=e.tokenised.match(t);o&&(e["num"+n]=o.length,e.tokenised=e.tokenised.replace(t,r),e.values.push(...o.map(i)))}function ly(e){const t=e.toString(),n={value:t,tokenised:t,values:[],numVars:0,numColors:0,numNumbers:0};return n.value.includes("var(--")&&uS(n,eL),uS(n,tL),uS(n,nL),n}function rL(e){return ly(e).values}function iL(e){const{values:t,numColors:n,numVars:r,tokenised:i}=ly(e),o=t.length;return s=>{let a=i;for(let l=0;ltypeof e=="number"?0:e;function nve(e){const t=rL(e);return iL(e)(t.map(tve))}const Xs={test:eve,parse:rL,createTransformer:iL,getAnimatableNone:nve},oL=(e,t)=>n=>`${n>0?t:e}`;function sL(e,t){return typeof e=="number"?n=>At(e,t,n):Xn.test(e)?JD(e,t):e.startsWith("var(")?oL(e,t):lL(e,t)}const aL=(e,t)=>{const n=[...e],r=n.length,i=e.map((o,s)=>sL(o,t[s]));return o=>{for(let s=0;s{const n={...e,...t},r={};for(const i in n)e[i]!==void 0&&t[i]!==void 0&&(r[i]=sL(e[i],t[i]));return i=>{for(const o in r)n[o]=r[o](i);return n}},lL=(e,t)=>{const n=Xs.createTransformer(t),r=ly(e),i=ly(t);return r.numVars===i.numVars&&r.numColors===i.numColors&&r.numNumbers>=i.numNumbers?Ns(aL(r.values,i.values),n):oL(e,t)},qf=(e,t,n)=>{const r=t-e;return r===0?1:(n-e)/r},uP=(e,t)=>n=>At(e,t,n);function ive(e){return typeof e=="number"?uP:typeof e=="string"?Xn.test(e)?JD:lL:Array.isArray(e)?aL:typeof e=="object"?rve:uP}function ove(e,t,n){const r=[],i=n||ive(e[0]),o=e.length-1;for(let s=0;st[0];e[0]>e[o-1]&&(e=[...e].reverse(),t=[...t].reverse());const s=ove(t,r,i),a=s.length,l=u=>{let c=0;if(a>1)for(;cl(Ks(e[0],e[o-1],u)):l}function sve(e,t){const n=e[e.length-1];for(let r=1;r<=t;r++){const i=qf(0,t,r);e.push(At(n,1,i))}}function ave(e){const t=[0];return sve(t,e.length-1),t}function lve(e,t){return e.map(n=>n*t)}function uve(e,t){return e.map(()=>t||WD).splice(0,e.length-1)}function uy({duration:e=300,keyframes:t,times:n,ease:r="easeInOut"}){const i=G0e(r)?r.map(aP):aP(r),o={done:!1,value:t[0]},s=lve(n&&n.length===t.length?n:ave(t),e),a=uL(s,t,{ease:Array.isArray(i)?i:uve(t,i)});return{calculatedDuration:e,next:l=>(o.value=a(l),o.done=l>=e,o)}}function cL(e,t){return t?e*(1e3/t):0}const cve=5;function dL(e,t,n){const r=Math.max(t-cve,0);return cL(n-e(r),t-r)}const cS=.001,dve=.01,cP=10,fve=.05,hve=1;function pve({duration:e=800,bounce:t=.25,velocity:n=0,mass:r=1}){let i,o;D0e(e<=Ds(cP));let s=1-t;s=Ks(fve,hve,s),e=Ks(dve,cP,No(e)),s<1?(i=u=>{const c=u*s,d=c*e,f=c-n,h=L2(u,s),p=Math.exp(-d);return cS-f/h*p},o=u=>{const d=u*s*e,f=d*n+n,h=Math.pow(s,2)*Math.pow(u,2)*e,p=Math.exp(-d),m=L2(Math.pow(u,2),s);return(-i(u)+cS>0?-1:1)*((f-h)*p)/m}):(i=u=>{const c=Math.exp(-u*e),d=(u-n)*e+1;return-cS+c*d},o=u=>{const c=Math.exp(-u*e),d=(n-u)*(e*e);return c*d});const a=5/e,l=mve(i,o,a);if(e=Ds(e),isNaN(l))return{stiffness:100,damping:10,duration:e};{const u=Math.pow(l,2)*r;return{stiffness:u,damping:s*2*Math.sqrt(r*u),duration:e}}}const gve=12;function mve(e,t,n){let r=n;for(let i=1;ie[n]!==void 0)}function bve(e){let t={velocity:0,stiffness:100,damping:10,mass:1,isResolvedFromDuration:!1,...e};if(!dP(e,vve)&&dP(e,yve)){const n=pve(e);t={...t,...n,velocity:0,mass:1},t.isResolvedFromDuration=!0}return t}function fL({keyframes:e,restDelta:t,restSpeed:n,...r}){const i=e[0],o=e[e.length-1],s={done:!1,value:i},{stiffness:a,damping:l,mass:u,velocity:c,duration:d,isResolvedFromDuration:f}=bve(r),h=c?-No(c):0,p=l/(2*Math.sqrt(a*u)),m=o-i,S=No(Math.sqrt(a/u)),v=Math.abs(m)<5;n||(n=v?.01:2),t||(t=v?.005:.5);let y;if(p<1){const g=L2(S,p);y=b=>{const _=Math.exp(-p*S*b);return o-_*((h+p*S*m)/g*Math.sin(g*b)+m*Math.cos(g*b))}}else if(p===1)y=g=>o-Math.exp(-S*g)*(m+(h+S*m)*g);else{const g=S*Math.sqrt(p*p-1);y=b=>{const _=Math.exp(-p*S*b),w=Math.min(g*b,300);return o-_*((h+p*S*m)*Math.sinh(w)+g*m*Math.cosh(w))/g}}return{calculatedDuration:f&&d||null,next:g=>{const b=y(g);if(f)s.done=g>=d;else{let _=h;g!==0&&(p<1?_=dL(y,g,b):_=0);const w=Math.abs(_)<=n,x=Math.abs(o-b)<=t;s.done=w&&x}return s.value=s.done?o:b,s}}}function fP({keyframes:e,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:i=10,bounceStiffness:o=500,modifyTarget:s,min:a,max:l,restDelta:u=.5,restSpeed:c}){const d=e[0],f={done:!1,value:d},h=T=>a!==void 0&&Tl,p=T=>a===void 0?l:l===void 0||Math.abs(a-T)-m*Math.exp(-T/r),g=T=>v+y(T),b=T=>{const P=y(T),E=g(T);f.done=Math.abs(P)<=u,f.value=f.done?v:E};let _,w;const x=T=>{h(f.value)&&(_=T,w=fL({keyframes:[f.value,p(f.value)],velocity:dL(g,T,f.value),damping:i,stiffness:o,restDelta:u,restSpeed:c}))};return x(0),{calculatedDuration:null,next:T=>{let P=!1;return!w&&_===void 0&&(P=!0,b(T),x(T)),_!==void 0&&T>_?w.next(T-_):(!P&&b(T),f)}}}const Sve=e=>{const t=({timestamp:n})=>e(n);return{start:()=>_t.update(t,!0),stop:()=>Uo(t),now:()=>$n.isProcessing?$n.timestamp:performance.now()}},hP=2e4;function pP(e){let t=0;const n=50;let r=e.next(t);for(;!r.done&&t=hP?1/0:t}const _ve={decay:fP,inertia:fP,tween:uy,keyframes:uy,spring:fL};function cy({autoplay:e=!0,delay:t=0,driver:n=Sve,keyframes:r,type:i="keyframes",repeat:o=0,repeatDelay:s=0,repeatType:a="loop",onPlay:l,onStop:u,onComplete:c,onUpdate:d,...f}){let h=1,p=!1,m,S;const v=()=>{S=new Promise(j=>{m=j})};v();let y;const g=_ve[i]||uy;let b;g!==uy&&typeof r[0]!="number"&&(b=uL([0,100],r,{clamp:!1}),r=[0,100]);const _=g({...f,keyframes:r});let w;a==="mirror"&&(w=g({...f,keyframes:[...r].reverse(),velocity:-(f.velocity||0)}));let x="idle",T=null,P=null,E=null;_.calculatedDuration===null&&o&&(_.calculatedDuration=pP(_));const{calculatedDuration:A}=_;let $=1/0,M=1/0;A!==null&&($=A+s,M=$*(o+1)-s);let C=0;const O=j=>{if(P===null)return;h>0&&(P=Math.min(P,j)),h<0&&(P=Math.min(j-M/h,P)),T!==null?C=T:C=Math.round(j-P)*h;const U=C-t*(h>=0?1:-1),G=h>=0?U<0:U>M;C=Math.max(U,0),x==="finished"&&T===null&&(C=M);let W=C,X=_;if(o){const Q=C/$;let J=Math.floor(Q),ne=Q%1;!ne&&Q>=1&&(ne=1),ne===1&&J--,J=Math.min(J,o+1);const te=!!(J%2);te&&(a==="reverse"?(ne=1-ne,s&&(ne-=s/$)):a==="mirror"&&(X=w));let xe=Ks(0,1,ne);C>M&&(xe=a==="reverse"&&te?1:0),W=xe*$}const Y=G?{done:!1,value:r[0]}:X.next(W);b&&(Y.value=b(Y.value));let{done:B}=Y;!G&&A!==null&&(B=h>=0?C>=M:C<=0);const H=T===null&&(x==="finished"||x==="running"&&B);return d&&d(Y.value),H&&R(),Y},I=()=>{y&&y.stop(),y=void 0},N=()=>{x="idle",I(),m(),v(),P=E=null},R=()=>{x="finished",c&&c(),I(),m()},D=()=>{if(p)return;y||(y=n(O));const j=y.now();l&&l(),T!==null?P=j-T:(!P||x==="finished")&&(P=j),x==="finished"&&v(),E=P,T=null,x="running",y.start()};e&&D();const L={then(j,U){return S.then(j,U)},get time(){return No(C)},set time(j){j=Ds(j),C=j,T!==null||!y||h===0?T=j:P=y.now()-j/h},get duration(){const j=_.calculatedDuration===null?pP(_):_.calculatedDuration;return No(j)},get speed(){return h},set speed(j){j===h||!y||(h=j,L.time=No(C))},get state(){return x},play:D,pause:()=>{x="paused",T=C},stop:()=>{p=!0,x!=="idle"&&(x="idle",u&&u(),N())},cancel:()=>{E!==null&&O(E),N()},complete:()=>{x="finished"},sample:j=>(P=0,O(j))};return L}const wve=new Set(["opacity","clipPath","filter","transform","backgroundColor"]),Hp=10,xve=2e4,Cve=(e,t)=>t.type==="spring"||e==="backgroundColor"||!zD(t.ease);function Tve(e,t,{onUpdate:n,onComplete:r,...i}){if(!(HD.waapi()&&wve.has(t)&&!i.repeatDelay&&i.repeatType!=="mirror"&&i.damping!==0&&i.type!=="inertia"))return!1;let s=!1,a,l;const u=()=>{l=new Promise(v=>{a=v})};u();let{keyframes:c,duration:d=300,ease:f,times:h}=i;if(Cve(t,i)){const v=cy({...i,repeat:0,delay:0});let y={done:!1,value:c[0]};const g=[];let b=0;for(;!y.done&&bp.cancel(),S=()=>{_t.update(m),a(),u()};return p.onfinish=()=>{e.set(F0e(c,i)),r&&r(),S()},{then(v,y){return l.then(v,y)},get time(){return No(p.currentTime||0)},set time(v){p.currentTime=Ds(v)},get speed(){return p.playbackRate},set speed(v){p.playbackRate=v},get duration(){return No(d)},play:()=>{s||(p.play(),Uo(m))},pause:()=>p.pause(),stop:()=>{if(s=!0,p.playState==="idle")return;const{currentTime:v}=p;if(v){const y=cy({...i,autoplay:!1});e.setWithVelocity(y.sample(v-Hp).value,y.sample(v).value,Hp)}S()},complete:()=>p.finish(),cancel:S}}function Eve({keyframes:e,delay:t,onUpdate:n,onComplete:r}){const i=()=>(n&&n(e[e.length-1]),r&&r(),{time:0,speed:1,duration:0,play:Qt,pause:Qt,stop:Qt,then:o=>(o(),Promise.resolve()),cancel:Qt,complete:Qt});return t?cy({keyframes:[0,1],duration:0,delay:t,onComplete:i}):i()}const Pve={type:"spring",stiffness:500,damping:25,restSpeed:10},Ave=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),kve={type:"keyframes",duration:.8},Ove={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Rve=(e,{keyframes:t})=>t.length>2?kve:El.has(e)?e.startsWith("scale")?Ave(t[1]):Pve:Ove,$2=(e,t)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Xs.test(t)||t==="0")&&!t.startsWith("url(")),Ive=new Set(["brightness","contrast","saturate","opacity"]);function Mve(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[r]=n.match(i1)||[];if(!r)return e;const i=n.replace(r,"");let o=Ive.has(t)?1:0;return r!==n&&(o*=100),t+"("+o+i+")"}const Nve=/([a-z-]*)\(.*?\)/g,F2={...Xs,getAnimatableNone:e=>{const t=e.match(Nve);return t?t.map(Mve).join(" "):e}},Dve={...TD,color:Xn,backgroundColor:Xn,outlineColor:Xn,fill:Xn,stroke:Xn,borderColor:Xn,borderTopColor:Xn,borderRightColor:Xn,borderBottomColor:Xn,borderLeftColor:Xn,filter:F2,WebkitFilter:F2},i3=e=>Dve[e];function hL(e,t){let n=i3(e);return n!==F2&&(n=Xs),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const pL=e=>/^0[^.\s]+$/.test(e);function Lve(e){if(typeof e=="number")return e===0;if(e!==null)return e==="none"||e==="0"||pL(e)}function $ve(e,t,n,r){const i=$2(t,n);let o;Array.isArray(n)?o=[...n]:o=[null,n];const s=r.from!==void 0?r.from:e.get();let a;const l=[];for(let u=0;ui=>{const o=gL(r,e)||{},s=o.delay||r.delay||0;let{elapsed:a=0}=r;a=a-Ds(s);const l=$ve(t,e,n,o),u=l[0],c=l[l.length-1],d=$2(e,u),f=$2(e,c);let h={keyframes:l,velocity:t.getVelocity(),ease:"easeOut",...o,delay:-a,onUpdate:p=>{t.set(p),o.onUpdate&&o.onUpdate(p)},onComplete:()=>{i(),o.onComplete&&o.onComplete()}};if(Fve(o)||(h={...h,...Rve(e,h)}),h.duration&&(h.duration=Ds(h.duration)),h.repeatDelay&&(h.repeatDelay=Ds(h.repeatDelay)),!d||!f||L0e.current||o.type===!1)return Eve(h);if(t.owner&&t.owner.current instanceof HTMLElement&&!t.owner.getProps().onUpdate){const p=Tve(t,e,h);if(p)return p}return cy(h)};function dy(e){return!!(_r(e)&&e.add)}const Bve=e=>/^\-?\d*\.?\d+$/.test(e);function s3(e,t){e.indexOf(t)===-1&&e.push(t)}function a3(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}class l3{constructor(){this.subscriptions=[]}add(t){return s3(this.subscriptions,t),()=>a3(this.subscriptions,t)}notify(t,n,r){const i=this.subscriptions.length;if(i)if(i===1)this.subscriptions[0](t,n,r);else for(let o=0;o!isNaN(parseFloat(e));class Vve{constructor(t,n={}){this.version="10.12.22",this.timeDelta=0,this.lastUpdated=0,this.canTrackVelocity=!1,this.events={},this.updateAndNotify=(r,i=!0)=>{this.prev=this.current,this.current=r;const{delta:o,timestamp:s}=$n;this.lastUpdated!==s&&(this.timeDelta=o,this.lastUpdated=s,_t.postRender(this.scheduleVelocityCheck)),this.prev!==this.current&&this.events.change&&this.events.change.notify(this.current),this.events.velocityChange&&this.events.velocityChange.notify(this.getVelocity()),i&&this.events.renderRequest&&this.events.renderRequest.notify(this.current)},this.scheduleVelocityCheck=()=>_t.postRender(this.velocityCheck),this.velocityCheck=({timestamp:r})=>{r!==this.lastUpdated&&(this.prev=this.current,this.events.velocityChange&&this.events.velocityChange.notify(this.getVelocity()))},this.hasAnimated=!1,this.prev=this.current=t,this.canTrackVelocity=jve(this.current),this.owner=n.owner}onChange(t){return this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new l3);const r=this.events[t].add(n);return t==="change"?()=>{r(),_t.read(()=>{this.events.change.getSize()||this.stop()})}:r}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t,n=!0){!n||!this.passiveEffect?this.updateAndNotify(t,n):this.passiveEffect(t,this.updateAndNotify)}setWithVelocity(t,n,r){this.set(n),this.prev=t,this.timeDelta=r}jump(t){this.updateAndNotify(t),this.prev=t,this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}get(){return this.current}getPrevious(){return this.prev}getVelocity(){return this.canTrackVelocity?cL(parseFloat(this.current)-parseFloat(this.prev),this.timeDelta):0}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function uc(e,t){return new Vve(e,t)}const mL=e=>t=>t.test(e),zve={test:e=>e==="auto",parse:e=>e},yL=[Pl,me,Ji,as,Xye,Kye,zve],id=e=>yL.find(mL(e)),Uve=[...yL,Xn,Xs],Gve=e=>Uve.find(mL(e));function Hve(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,uc(n))}function qve(e,t){const n=s1(e,t);let{transitionEnd:r={},transition:i={},...o}=n?e.makeTargetAnimatable(n,!1):{};o={...o,...r};for(const s in o){const a=u0e(o[s]);Hve(e,s,a)}}function Wve(e,t,n){var r,i;const o=Object.keys(t).filter(a=>!e.hasValue(a)),s=o.length;if(s)for(let a=0;al.remove(d))),u.push(m)}return s&&Promise.all(u).then(()=>{s&&qve(e,s)}),u}function B2(e,t,n={}){const r=s1(e,t,n.custom);let{transition:i=e.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(i=n.transitionOverride);const o=r?()=>Promise.all(vL(e,r,n)):()=>Promise.resolve(),s=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:u=0,staggerChildren:c,staggerDirection:d}=i;return Qve(e,t,u+l,c,d,n)}:()=>Promise.resolve(),{when:a}=i;if(a){const[l,u]=a==="beforeChildren"?[o,s]:[s,o];return l().then(()=>u())}else return Promise.all([o(),s(n.delay)])}function Qve(e,t,n=0,r=0,i=1,o){const s=[],a=(e.variantChildren.size-1)*r,l=i===1?(u=0)=>u*r:(u=0)=>a-u*r;return Array.from(e.variantChildren).sort(Zve).forEach((u,c)=>{u.notify("AnimationStart",t),s.push(B2(u,t,{...o,delay:n+l(c)}).then(()=>u.notify("AnimationComplete",t)))}),Promise.all(s)}function Zve(e,t){return e.sortNodePosition(t)}function Jve(e,t,n={}){e.notify("AnimationStart",t);let r;if(Array.isArray(t)){const i=t.map(o=>B2(e,o,n));r=Promise.all(i)}else if(typeof t=="string")r=B2(e,t,n);else{const i=typeof t=="function"?s1(e,t,n.custom):t;r=Promise.all(vL(e,i,n))}return r.then(()=>e.notify("AnimationComplete",t))}const e1e=[...UC].reverse(),t1e=UC.length;function n1e(e){return t=>Promise.all(t.map(({animation:n,options:r})=>Jve(e,n,r)))}function r1e(e){let t=n1e(e);const n=o1e();let r=!0;const i=(l,u)=>{const c=s1(e,u);if(c){const{transition:d,transitionEnd:f,...h}=c;l={...l,...h,...f}}return l};function o(l){t=l(e)}function s(l,u){const c=e.getProps(),d=e.getVariantContext(!0)||{},f=[],h=new Set;let p={},m=1/0;for(let v=0;vm&&_;const E=Array.isArray(b)?b:[b];let A=E.reduce(i,{});w===!1&&(A={});const{prevResolvedValues:$={}}=g,M={...$,...A},C=O=>{P=!0,h.delete(O),g.needsAnimating[O]=!0};for(const O in M){const I=A[O],N=$[O];p.hasOwnProperty(O)||(I!==N?ay(I)&&ay(N)?!jD(I,N)||T?C(O):g.protectedKeys[O]=!0:I!==void 0?C(O):h.add(O):I!==void 0&&h.has(O)?C(O):g.protectedKeys[O]=!0)}g.prevProp=b,g.prevResolvedValues=A,g.isActive&&(p={...p,...A}),r&&e.blockInitialAnimation&&(P=!1),P&&!x&&f.push(...E.map(O=>({animation:O,options:{type:y,...l}})))}if(h.size){const v={};h.forEach(y=>{const g=e.getBaseTarget(y);g!==void 0&&(v[y]=g)}),f.push({animation:v})}let S=!!f.length;return r&&c.initial===!1&&!e.manuallyAnimateOnMount&&(S=!1),r=!1,S?t(f):Promise.resolve()}function a(l,u,c){var d;if(n[l].isActive===u)return Promise.resolve();(d=e.variantChildren)===null||d===void 0||d.forEach(h=>{var p;return(p=h.animationState)===null||p===void 0?void 0:p.setActive(l,u)}),n[l].isActive=u;const f=s(c,l);for(const h in n)n[h].protectedKeys={};return f}return{animateChanges:s,setActive:a,setAnimateFunction:o,getState:()=>n}}function i1e(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!jD(t,e):!1}function ba(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function o1e(){return{animate:ba(!0),whileInView:ba(),whileHover:ba(),whileTap:ba(),whileDrag:ba(),whileFocus:ba(),exit:ba()}}class s1e extends ua{constructor(t){super(t),t.animationState||(t.animationState=r1e(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();this.unmount(),n1(t)&&(this.unmount=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){}}let a1e=0;class l1e extends ua{constructor(){super(...arguments),this.id=a1e++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n,custom:r}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===i)return;const o=this.node.animationState.setActive("exit",!t,{custom:r??this.node.getProps().custom});n&&!t&&o.then(()=>n(this.id))}mount(){const{register:t}=this.node.presenceContext||{};t&&(this.unmount=t(this.id))}unmount(){}}const u1e={animation:{Feature:s1e},exit:{Feature:l1e}},gP=(e,t)=>Math.abs(e-t);function c1e(e,t){const n=gP(e.x,t.x),r=gP(e.y,t.y);return Math.sqrt(n**2+r**2)}class bL{constructor(t,n,{transformPagePoint:r}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const u=fS(this.lastMoveEventInfo,this.history),c=this.startEvent!==null,d=c1e(u.offset,{x:0,y:0})>=3;if(!c&&!d)return;const{point:f}=u,{timestamp:h}=$n;this.history.push({...f,timestamp:h});const{onStart:p,onMove:m}=this.handlers;c||(p&&p(this.lastMoveEvent,u),this.startEvent=this.lastMoveEvent),m&&m(this.lastMoveEvent,u)},this.handlePointerMove=(u,c)=>{this.lastMoveEvent=u,this.lastMoveEventInfo=dS(c,this.transformPagePoint),_t.update(this.updatePoint,!0)},this.handlePointerUp=(u,c)=>{if(this.end(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const{onEnd:d,onSessionEnd:f}=this.handlers,h=fS(u.type==="pointercancel"?this.lastMoveEventInfo:dS(c,this.transformPagePoint),this.history);this.startEvent&&d&&d(u,h),f&&f(u,h)},!DD(t))return;this.handlers=n,this.transformPagePoint=r;const i=o1(t),o=dS(i,this.transformPagePoint),{point:s}=o,{timestamp:a}=$n;this.history=[{...s,timestamp:a}];const{onSessionStart:l}=n;l&&l(t,fS(o,this.history)),this.removeListeners=Ns(Mo(window,"pointermove",this.handlePointerMove),Mo(window,"pointerup",this.handlePointerUp),Mo(window,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),Uo(this.updatePoint)}}function dS(e,t){return t?{point:t(e.point)}:e}function mP(e,t){return{x:e.x-t.x,y:e.y-t.y}}function fS({point:e},t){return{point:e,delta:mP(e,SL(t)),offset:mP(e,d1e(t)),velocity:f1e(t,.1)}}function d1e(e){return e[0]}function SL(e){return e[e.length-1]}function f1e(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null;const i=SL(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>Ds(t)));)n--;if(!r)return{x:0,y:0};const o=No(i.timestamp-r.timestamp);if(o===0)return{x:0,y:0};const s={x:(i.x-r.x)/o,y:(i.y-r.y)/o};return s.x===1/0&&(s.x=0),s.y===1/0&&(s.y=0),s}function Ir(e){return e.max-e.min}function j2(e,t=0,n=.01){return Math.abs(e-t)<=n}function yP(e,t,n,r=.5){e.origin=r,e.originPoint=At(t.min,t.max,e.origin),e.scale=Ir(n)/Ir(t),(j2(e.scale,1,1e-4)||isNaN(e.scale))&&(e.scale=1),e.translate=At(n.min,n.max,e.origin)-e.originPoint,(j2(e.translate)||isNaN(e.translate))&&(e.translate=0)}function Md(e,t,n,r){yP(e.x,t.x,n.x,r?r.originX:void 0),yP(e.y,t.y,n.y,r?r.originY:void 0)}function vP(e,t,n){e.min=n.min+t.min,e.max=e.min+Ir(t)}function h1e(e,t,n){vP(e.x,t.x,n.x),vP(e.y,t.y,n.y)}function bP(e,t,n){e.min=t.min-n.min,e.max=e.min+Ir(t)}function Nd(e,t,n){bP(e.x,t.x,n.x),bP(e.y,t.y,n.y)}function p1e(e,{min:t,max:n},r){return t!==void 0&&en&&(e=r?At(n,e,r.max):Math.min(e,n)),e}function SP(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function g1e(e,{top:t,left:n,bottom:r,right:i}){return{x:SP(e.x,n,i),y:SP(e.y,t,r)}}function _P(e,t){let n=t.min-e.min,r=t.max-e.max;return t.max-t.minr?n=qf(t.min,t.max-r,e.min):r>i&&(n=qf(e.min,e.max-i,t.min)),Ks(0,1,n)}function v1e(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const V2=.35;function b1e(e=V2){return e===!1?e=0:e===!0&&(e=V2),{x:wP(e,"left","right"),y:wP(e,"top","bottom")}}function wP(e,t,n){return{min:xP(e,t),max:xP(e,n)}}function xP(e,t){return typeof e=="number"?e:e[t]||0}const CP=()=>({translate:0,scale:1,origin:0,originPoint:0}),gu=()=>({x:CP(),y:CP()}),TP=()=>({min:0,max:0}),Wt=()=>({x:TP(),y:TP()});function Li(e){return[e("x"),e("y")]}function _L({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function S1e({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function _1e(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),r=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function hS(e){return e===void 0||e===1}function z2({scale:e,scaleX:t,scaleY:n}){return!hS(e)||!hS(t)||!hS(n)}function Ca(e){return z2(e)||wL(e)||e.z||e.rotate||e.rotateX||e.rotateY}function wL(e){return EP(e.x)||EP(e.y)}function EP(e){return e&&e!=="0%"}function fy(e,t,n){const r=e-n,i=t*r;return n+i}function PP(e,t,n,r,i){return i!==void 0&&(e=fy(e,i,r)),fy(e,n,r)+t}function U2(e,t=0,n=1,r,i){e.min=PP(e.min,t,n,r,i),e.max=PP(e.max,t,n,r,i)}function xL(e,{x:t,y:n}){U2(e.x,t.translate,t.scale,t.originPoint),U2(e.y,n.translate,n.scale,n.originPoint)}function w1e(e,t,n,r=!1){const i=n.length;if(!i)return;t.x=t.y=1;let o,s;for(let a=0;a1.0000000000001||e<.999999999999?e:1}function fs(e,t){e.min=e.min+t,e.max=e.max+t}function kP(e,t,[n,r,i]){const o=t[i]!==void 0?t[i]:.5,s=At(e.min,e.max,o);U2(e,t[n],t[r],s,t.scale)}const x1e=["x","scaleX","originX"],C1e=["y","scaleY","originY"];function mu(e,t){kP(e.x,t,x1e),kP(e.y,t,C1e)}function CL(e,t){return _L(_1e(e.getBoundingClientRect(),t))}function T1e(e,t,n){const r=CL(e,n),{scroll:i}=t;return i&&(fs(r.x,i.offset.x),fs(r.y,i.offset.y)),r}const E1e=new WeakMap;class P1e{constructor(t){this.openGlobalLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Wt(),this.visualElement=t}start(t,{snapToCursor:n=!1}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const i=l=>{this.stopAnimation(),n&&this.snapToCursor(o1(l,"page").point)},o=(l,u)=>{const{drag:c,dragPropagation:d,onDragStart:f}=this.getProps();if(c&&!d&&(this.openGlobalLock&&this.openGlobalLock(),this.openGlobalLock=$D(c),!this.openGlobalLock))return;this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Li(p=>{let m=this.getAxisMotionValue(p).get()||0;if(Ji.test(m)){const{projection:S}=this.visualElement;if(S&&S.layout){const v=S.layout.layoutBox[p];v&&(m=Ir(v)*(parseFloat(m)/100))}}this.originPoint[p]=m}),f&&_t.update(()=>f(l,u),!1,!0);const{animationState:h}=this.visualElement;h&&h.setActive("whileDrag",!0)},s=(l,u)=>{const{dragPropagation:c,dragDirectionLock:d,onDirectionLock:f,onDrag:h}=this.getProps();if(!c&&!this.openGlobalLock)return;const{offset:p}=u;if(d&&this.currentDirection===null){this.currentDirection=A1e(p),this.currentDirection!==null&&f&&f(this.currentDirection);return}this.updateAxis("x",u.point,p),this.updateAxis("y",u.point,p),this.visualElement.render(),h&&h(l,u)},a=(l,u)=>this.stop(l,u);this.panSession=new bL(t,{onSessionStart:i,onStart:o,onMove:s,onSessionEnd:a},{transformPagePoint:this.visualElement.getTransformPagePoint()})}stop(t,n){const r=this.isDragging;if(this.cancel(),!r)return;const{velocity:i}=n;this.startAnimation(i);const{onDragEnd:o}=this.getProps();o&&_t.update(()=>o(t,n))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:r}=this.getProps();!r&&this.openGlobalLock&&(this.openGlobalLock(),this.openGlobalLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,r){const{drag:i}=this.getProps();if(!r||!qp(t,i,this.currentDirection))return;const o=this.getAxisMotionValue(t);let s=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(s=p1e(s,this.constraints[t],this.elastic[t])),o.set(s)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),{layout:r}=this.visualElement.projection||{},i=this.constraints;t&&hu(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=g1e(r.layoutBox,t):this.constraints=!1,this.elastic=b1e(n),i!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&Li(o=>{this.getAxisMotionValue(o)&&(this.constraints[o]=v1e(r.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!hu(t))return!1;const r=t.current,{projection:i}=this.visualElement;if(!i||!i.layout)return!1;const o=T1e(r,i.root,this.visualElement.getTransformPagePoint());let s=m1e(i.layout.layoutBox,o);if(n){const a=n(S1e(s));this.hasMutatedConstraints=!!a,a&&(s=_L(a))}return s}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:i,dragTransition:o,dragSnapToOrigin:s,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},u=Li(c=>{if(!qp(c,n,this.currentDirection))return;let d=l&&l[c]||{};s&&(d={min:0,max:0});const f=i?200:1e6,h=i?40:1e7,p={type:"inertia",velocity:r?t[c]:0,bounceStiffness:f,bounceDamping:h,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(c,p)});return Promise.all(u).then(a)}startAxisValueAnimation(t,n){const r=this.getAxisMotionValue(t);return r.start(o3(t,r,0,n))}stopAnimation(){Li(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const n="_drag"+t.toUpperCase(),r=this.visualElement.getProps(),i=r[n];return i||this.visualElement.getValue(t,(r.initial?r.initial[t]:void 0)||0)}snapToCursor(t){Li(n=>{const{drag:r}=this.getProps();if(!qp(n,r,this.currentDirection))return;const{projection:i}=this.visualElement,o=this.getAxisMotionValue(n);if(i&&i.layout){const{min:s,max:a}=i.layout.layoutBox[n];o.set(t[n]-At(s,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!hu(n)||!r||!this.constraints)return;this.stopAnimation();const i={x:0,y:0};Li(s=>{const a=this.getAxisMotionValue(s);if(a){const l=a.get();i[s]=y1e({min:l,max:l},this.constraints[s])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),Li(s=>{if(!qp(s,t,null))return;const a=this.getAxisMotionValue(s),{min:l,max:u}=this.constraints[s];a.set(At(l,u,i[s]))})}addListeners(){if(!this.visualElement.current)return;E1e.set(this.visualElement,this);const t=this.visualElement.current,n=Mo(t,"pointerdown",l=>{const{drag:u,dragListener:c=!0}=this.getProps();u&&c&&this.start(l)}),r=()=>{const{dragConstraints:l}=this.getProps();hu(l)&&(this.constraints=this.resolveRefConstraints())},{projection:i}=this.visualElement,o=i.addEventListener("measure",r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),r();const s=Ao(window,"resize",()=>this.scalePositionWithinConstraints()),a=i.addEventListener("didUpdate",({delta:l,hasLayoutChanged:u})=>{this.isDragging&&u&&(Li(c=>{const d=this.getAxisMotionValue(c);d&&(this.originPoint[c]+=l[c].translate,d.set(d.get()+l[c].translate))}),this.visualElement.render())});return()=>{s(),n(),o(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:r=!1,dragPropagation:i=!1,dragConstraints:o=!1,dragElastic:s=V2,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:i,dragConstraints:o,dragElastic:s,dragMomentum:a}}}function qp(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function A1e(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class k1e extends ua{constructor(t){super(t),this.removeGroupControls=Qt,this.removeListeners=Qt,this.controls=new P1e(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Qt}unmount(){this.removeGroupControls(),this.removeListeners()}}const OP=e=>(t,n)=>{e&&_t.update(()=>e(t,n))};class O1e extends ua{constructor(){super(...arguments),this.removePointerDownListener=Qt}onPointerDown(t){this.session=new bL(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint()})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:i}=this.node.getProps();return{onSessionStart:OP(t),onStart:OP(n),onMove:r,onEnd:(o,s)=>{delete this.session,i&&_t.update(()=>i(o,s))}}}mount(){this.removePointerDownListener=Mo(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}function R1e(){const e=k.useContext(Lh);if(e===null)return[!0,null];const{isPresent:t,onExitComplete:n,register:r}=e,i=k.useId();return k.useEffect(()=>r(i),[]),!t&&n?[!1,()=>n&&n(i)]:[!0]}function C4e(){return I1e(k.useContext(Lh))}function I1e(e){return e===null?!0:e.isPresent}const Pg={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function RP(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const od={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(me.test(e))e=parseFloat(e);else return e;const n=RP(e,t.target.x),r=RP(e,t.target.y);return`${n}% ${r}%`}},M1e={correct:(e,{treeScale:t,projectionDelta:n})=>{const r=e,i=Xs.parse(e);if(i.length>5)return r;const o=Xs.createTransformer(e),s=typeof i[0]!="number"?1:0,a=n.x.scale*t.x,l=n.y.scale*t.y;i[0+s]/=a,i[1+s]/=l;const u=At(a,l,.5);return typeof i[2+s]=="number"&&(i[2+s]/=u),typeof i[3+s]=="number"&&(i[3+s]/=u),o(i)}};class N1e extends We.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r,layoutId:i}=this.props,{projection:o}=t;Vye(D1e),o&&(n.group&&n.group.add(o),r&&r.register&&i&&r.register(o),o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Pg.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:r,drag:i,isPresent:o}=this.props,s=r.projection;return s&&(s.isPresent=o,i||t.layoutDependency!==n||n===void 0?s.willUpdate():this.safeToRemove(),t.isPresent!==o&&(o?s.promote():s.relegate()||_t.postRender(()=>{const a=s.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),queueMicrotask(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:i}=t;i&&(i.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(i),r&&r.deregister&&r.deregister(i))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function TL(e){const[t,n]=R1e(),r=k.useContext(HC);return We.createElement(N1e,{...e,layoutGroup:r,switchLayoutGroup:k.useContext(SD),isPresent:t,safeToRemove:n})}const D1e={borderRadius:{...od,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:od,borderTopRightRadius:od,borderBottomLeftRadius:od,borderBottomRightRadius:od,boxShadow:M1e},EL=["TopLeft","TopRight","BottomLeft","BottomRight"],L1e=EL.length,IP=e=>typeof e=="string"?parseFloat(e):e,MP=e=>typeof e=="number"||me.test(e);function $1e(e,t,n,r,i,o){i?(e.opacity=At(0,n.opacity!==void 0?n.opacity:1,F1e(r)),e.opacityExit=At(t.opacity!==void 0?t.opacity:1,0,B1e(r))):o&&(e.opacity=At(t.opacity!==void 0?t.opacity:1,n.opacity!==void 0?n.opacity:1,r));for(let s=0;srt?1:n(qf(e,t,r))}function DP(e,t){e.min=t.min,e.max=t.max}function Vr(e,t){DP(e.x,t.x),DP(e.y,t.y)}function LP(e,t,n,r,i){return e-=t,e=fy(e,1/n,r),i!==void 0&&(e=fy(e,1/i,r)),e}function j1e(e,t=0,n=1,r=.5,i,o=e,s=e){if(Ji.test(t)&&(t=parseFloat(t),t=At(s.min,s.max,t/100)-s.min),typeof t!="number")return;let a=At(o.min,o.max,r);e===o&&(a-=t),e.min=LP(e.min,t,n,a,i),e.max=LP(e.max,t,n,a,i)}function $P(e,t,[n,r,i],o,s){j1e(e,t[n],t[r],t[i],t.scale,o,s)}const V1e=["x","scaleX","originX"],z1e=["y","scaleY","originY"];function FP(e,t,n,r){$P(e.x,t,V1e,n?n.x:void 0,r?r.x:void 0),$P(e.y,t,z1e,n?n.y:void 0,r?r.y:void 0)}function BP(e){return e.translate===0&&e.scale===1}function AL(e){return BP(e.x)&&BP(e.y)}function G2(e,t){return e.x.min===t.x.min&&e.x.max===t.x.max&&e.y.min===t.y.min&&e.y.max===t.y.max}function jP(e){return Ir(e.x)/Ir(e.y)}class U1e{constructor(){this.members=[]}add(t){s3(this.members,t),t.scheduleRender()}remove(t){if(a3(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(i=>t===i);if(n===0)return!1;let r;for(let i=n;i>=0;i--){const o=this.members[i];if(o.isPresent!==!1){r=o;break}}return r?(this.promote(r),!0):!1}promote(t,n){const r=this.lead;if(t!==r&&(this.prevLead=r,this.lead=t,t.show(),r)){r.instance&&r.scheduleRender(),t.scheduleRender(),t.resumeFrom=r,n&&(t.resumeFrom.preserveOpacity=!0),r.snapshot&&(t.snapshot=r.snapshot,t.snapshot.latestValues=r.animationValues||r.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:i}=t.options;i===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:r}=t;n.onExitComplete&&n.onExitComplete(),r&&r.options.onExitComplete&&r.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function VP(e,t,n){let r="";const i=e.x.translate/t.x,o=e.y.translate/t.y;if((i||o)&&(r=`translate3d(${i}px, ${o}px, 0) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){const{rotate:l,rotateX:u,rotateY:c}=n;l&&(r+=`rotate(${l}deg) `),u&&(r+=`rotateX(${u}deg) `),c&&(r+=`rotateY(${c}deg) `)}const s=e.x.scale*t.x,a=e.y.scale*t.y;return(s!==1||a!==1)&&(r+=`scale(${s}, ${a})`),r||"none"}const G1e=(e,t)=>e.depth-t.depth;class H1e{constructor(){this.children=[],this.isDirty=!1}add(t){s3(this.children,t),this.isDirty=!0}remove(t){a3(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(G1e),this.isDirty=!1,this.children.forEach(t)}}function q1e(e,t){const n=performance.now(),r=({timestamp:i})=>{const o=i-n;o>=t&&(Uo(r),e(o-t))};return _t.read(r,!0),()=>Uo(r)}function W1e(e){window.MotionDebug&&window.MotionDebug.record(e)}function K1e(e){return e instanceof SVGElement&&e.tagName!=="svg"}function X1e(e,t,n){const r=_r(e)?e:uc(e);return r.start(o3("",r,t,n)),r.animation}const zP=["","X","Y","Z"],UP=1e3;let Y1e=0;const Ta={type:"projectionFrame",totalNodes:0,resolvedTargetDeltas:0,recalculatedProjection:0};function kL({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(s={},a=t==null?void 0:t()){this.id=Y1e++,this.animationId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{Ta.totalNodes=Ta.resolvedTargetDeltas=Ta.recalculatedProjection=0,this.nodes.forEach(J1e),this.nodes.forEach(ibe),this.nodes.forEach(obe),this.nodes.forEach(ebe),W1e(Ta)},this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=s,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;lthis.root.updateBlockedByResize=!1;e(s,()=>{this.root.updateBlockedByResize=!0,d&&d(),d=q1e(f,250),Pg.hasAnimatedSinceResize&&(Pg.hasAnimatedSinceResize=!1,this.nodes.forEach(HP))})}l&&this.root.registerSharedNode(l,this),this.options.animate!==!1&&c&&(l||u)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:f,hasRelativeTargetChanged:h,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const m=this.options.transition||c.getDefaultTransition()||cbe,{onLayoutAnimationStart:S,onLayoutAnimationComplete:v}=c.getProps(),y=!this.targetLayout||!G2(this.targetLayout,p)||h,g=!f&&h;if(this.options.layoutRoot||this.resumeFrom&&this.resumeFrom.instance||g||f&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0),this.setAnimationOrigin(d,g);const b={...gL(m,"layout"),onPlay:S,onComplete:v};(c.shouldReduceMotion||this.options.layoutRoot)&&(b.delay=0,b.type=!1),this.startAnimation(b)}else f||HP(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const s=this.getStack();s&&s.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,Uo(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(sbe),this.animationId++)}getTransformTemplate(){const{visualElement:s}=this.options;return s&&s.getProps().transformTemplate}willUpdate(s=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let c=0;cthis.update()))}clearAllSnapshots(){this.nodes.forEach(tbe),this.sharedNodes.forEach(abe)}scheduleUpdateProjection(){_t.preRender(this.updateProjection,!1,!0)}scheduleCheckAfterUnmount(){_t.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure())}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l{const _=b/1e3;qP(d.x,s.x,_),qP(d.y,s.y,_),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Nd(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),lbe(this.relativeTarget,this.relativeTargetOrigin,f,_),g&&G2(this.relativeTarget,g)&&(this.isProjectionDirty=!1),g||(g=Wt()),Vr(g,this.relativeTarget)),m&&(this.animationValues=c,$1e(c,u,this.latestValues,_,y,v)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=_},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(s){this.notifyListeners("animationStart"),this.currentAnimation&&this.currentAnimation.stop(),this.resumingFrom&&this.resumingFrom.currentAnimation&&this.resumingFrom.currentAnimation.stop(),this.pendingAnimation&&(Uo(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=_t.update(()=>{Pg.hasAnimatedSinceResize=!0,this.currentAnimation=X1e(0,UP,{...s,onUpdate:a=>{this.mixTargetDelta(a),s.onUpdate&&s.onUpdate(a)},onComplete:()=>{s.onComplete&&s.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const s=this.getStack();s&&s.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(UP),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const s=this.getLead();let{targetWithTransforms:a,target:l,layout:u,latestValues:c}=s;if(!(!a||!l||!u)){if(this!==s&&this.layout&&u&&OL(this.options.animationType,this.layout.layoutBox,u.layoutBox)){l=this.target||Wt();const d=Ir(this.layout.layoutBox.x);l.x.min=s.target.x.min,l.x.max=l.x.min+d;const f=Ir(this.layout.layoutBox.y);l.y.min=s.target.y.min,l.y.max=l.y.min+f}Vr(a,l),mu(a,c),Md(this.projectionDeltaWithTransform,this.layoutCorrected,a,c)}}registerSharedNode(s,a){this.sharedNodes.has(s)||this.sharedNodes.set(s,new U1e),this.sharedNodes.get(s).add(a);const u=a.options.initialPromotionConfig;a.promote({transition:u?u.transition:void 0,preserveFollowOpacity:u&&u.shouldPreserveFollowOpacity?u.shouldPreserveFollowOpacity(a):void 0})}isLead(){const s=this.getStack();return s?s.lead===this:!0}getLead(){var s;const{layoutId:a}=this.options;return a?((s=this.getStack())===null||s===void 0?void 0:s.lead)||this:this}getPrevLead(){var s;const{layoutId:a}=this.options;return a?(s=this.getStack())===null||s===void 0?void 0:s.prevLead:void 0}getStack(){const{layoutId:s}=this.options;if(s)return this.root.sharedNodes.get(s)}promote({needsReset:s,transition:a,preserveFollowOpacity:l}={}){const u=this.getStack();u&&u.promote(this,l),s&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const s=this.getStack();return s?s.relegate(this):!1}resetRotation(){const{visualElement:s}=this.options;if(!s)return;let a=!1;const{latestValues:l}=s;if((l.rotate||l.rotateX||l.rotateY||l.rotateZ)&&(a=!0),!a)return;const u={};for(let c=0;c{var a;return(a=s.currentAnimation)===null||a===void 0?void 0:a.stop()}),this.root.nodes.forEach(GP),this.root.sharedNodes.clear()}}}function Q1e(e){e.updateLayout()}function Z1e(e){var t;const n=((t=e.resumeFrom)===null||t===void 0?void 0:t.snapshot)||e.snapshot;if(e.isLead()&&e.layout&&n&&e.hasListeners("didUpdate")){const{layoutBox:r,measuredBox:i}=e.layout,{animationType:o}=e.options,s=n.source!==e.layout.source;o==="size"?Li(d=>{const f=s?n.measuredBox[d]:n.layoutBox[d],h=Ir(f);f.min=r[d].min,f.max=f.min+h}):OL(o,n.layoutBox,r)&&Li(d=>{const f=s?n.measuredBox[d]:n.layoutBox[d],h=Ir(r[d]);f.max=f.min+h,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[d].max=e.relativeTarget[d].min+h)});const a=gu();Md(a,r,n.layoutBox);const l=gu();s?Md(l,e.applyTransform(i,!0),n.measuredBox):Md(l,r,n.layoutBox);const u=!AL(a);let c=!1;if(!e.resumeFrom){const d=e.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:f,layout:h}=d;if(f&&h){const p=Wt();Nd(p,n.layoutBox,f.layoutBox);const m=Wt();Nd(m,r,h.layoutBox),G2(p,m)||(c=!0),d.options.layoutRoot&&(e.relativeTarget=m,e.relativeTargetOrigin=p,e.relativeParent=d)}}}e.notifyListeners("didUpdate",{layout:r,snapshot:n,delta:l,layoutDelta:a,hasLayoutChanged:u,hasRelativeTargetChanged:c})}else if(e.isLead()){const{onExitComplete:r}=e.options;r&&r()}e.options.transition=void 0}function J1e(e){Ta.totalNodes++,e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function ebe(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function tbe(e){e.clearSnapshot()}function GP(e){e.clearMeasurements()}function nbe(e){e.isLayoutDirty=!1}function rbe(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function HP(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function ibe(e){e.resolveTargetDelta()}function obe(e){e.calcProjection()}function sbe(e){e.resetRotation()}function abe(e){e.removeLeadSnapshot()}function qP(e,t,n){e.translate=At(t.translate,0,n),e.scale=At(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function WP(e,t,n,r){e.min=At(t.min,n.min,r),e.max=At(t.max,n.max,r)}function lbe(e,t,n,r){WP(e.x,t.x,n.x,r),WP(e.y,t.y,n.y,r)}function ube(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const cbe={duration:.45,ease:[.4,0,.1,1]};function KP(e){e.min=Math.round(e.min*2)/2,e.max=Math.round(e.max*2)/2}function dbe(e){KP(e.x),KP(e.y)}function OL(e,t,n){return e==="position"||e==="preserve-aspect"&&!j2(jP(t),jP(n),.2)}const fbe=kL({attachResizeListener:(e,t)=>Ao(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),pS={current:void 0},RL=kL({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!pS.current){const e=new fbe({});e.mount(window),e.setOptions({layoutScroll:!0}),pS.current=e}return pS.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),hbe={pan:{Feature:O1e},drag:{Feature:k1e,ProjectionNode:RL,MeasureLayout:TL}},pbe=/var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/;function gbe(e){const t=pbe.exec(e);if(!t)return[,];const[,n,r]=t;return[n,r]}function H2(e,t,n=1){const[r,i]=gbe(e);if(!r)return;const o=window.getComputedStyle(t).getPropertyValue(r);return o?o.trim():M2(i)?H2(i,t,n+1):i}function mbe(e,{...t},n){const r=e.current;if(!(r instanceof Element))return{target:t,transitionEnd:n};n&&(n={...n}),e.values.forEach(i=>{const o=i.get();if(!M2(o))return;const s=H2(o,r);s&&i.set(s)});for(const i in t){const o=t[i];if(!M2(o))continue;const s=H2(o,r);s&&(t[i]=s,n||(n={}),n[i]===void 0&&(n[i]=o))}return{target:t,transitionEnd:n}}const ybe=new Set(["width","height","top","left","right","bottom","x","y","translateX","translateY"]),IL=e=>ybe.has(e),vbe=e=>Object.keys(e).some(IL),XP=e=>e===Pl||e===me,YP=(e,t)=>parseFloat(e.split(", ")[t]),QP=(e,t)=>(n,{transform:r})=>{if(r==="none"||!r)return 0;const i=r.match(/^matrix3d\((.+)\)$/);if(i)return YP(i[1],t);{const o=r.match(/^matrix\((.+)\)$/);return o?YP(o[1],e):0}},bbe=new Set(["x","y","z"]),Sbe=$h.filter(e=>!bbe.has(e));function _be(e){const t=[];return Sbe.forEach(n=>{const r=e.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t.length&&e.render(),t}const cc={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:QP(4,13),y:QP(5,14)};cc.translateX=cc.x;cc.translateY=cc.y;const wbe=(e,t,n)=>{const r=t.measureViewportBox(),i=t.current,o=getComputedStyle(i),{display:s}=o,a={};s==="none"&&t.setStaticValue("display",e.display||"block"),n.forEach(u=>{a[u]=cc[u](r,o)}),t.render();const l=t.measureViewportBox();return n.forEach(u=>{const c=t.getValue(u);c&&c.jump(a[u]),e[u]=cc[u](l,o)}),e},xbe=(e,t,n={},r={})=>{t={...t},r={...r};const i=Object.keys(t).filter(IL);let o=[],s=!1;const a=[];if(i.forEach(l=>{const u=e.getValue(l);if(!e.hasValue(l))return;let c=n[l],d=id(c);const f=t[l];let h;if(ay(f)){const p=f.length,m=f[0]===null?1:0;c=f[m],d=id(c);for(let S=m;S=0?window.pageYOffset:null,u=wbe(t,e,a);return o.length&&o.forEach(([c,d])=>{e.getValue(c).set(d)}),e.render(),t1&&l!==null&&window.scrollTo({top:l}),{target:u,transitionEnd:r}}else return{target:t,transitionEnd:r}};function Cbe(e,t,n,r){return vbe(t)?xbe(e,t,n,r):{target:t,transitionEnd:r}}const Tbe=(e,t,n,r)=>{const i=mbe(e,t,r);return t=i.target,r=i.transitionEnd,Cbe(e,t,n,r)},q2={current:null},ML={current:!1};function Ebe(){if(ML.current=!0,!!t1)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>q2.current=e.matches;e.addListener(t),t()}else q2.current=!1}function Pbe(e,t,n){const{willChange:r}=t;for(const i in t){const o=t[i],s=n[i];if(_r(o))e.addValue(i,o),dy(r)&&r.add(i);else if(_r(s))e.addValue(i,uc(o,{owner:e})),dy(r)&&r.remove(i);else if(s!==o)if(e.hasValue(i)){const a=e.getValue(i);!a.hasAnimated&&a.set(o)}else{const a=e.getStaticValue(i);e.addValue(i,uc(a!==void 0?a:o,{owner:e}))}}for(const i in n)t[i]===void 0&&e.removeValue(i);return t}const ZP=new WeakMap,NL=Object.keys(Hf),Abe=NL.length,JP=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"],kbe=GC.length;class Obe{constructor({parent:t,props:n,presenceContext:r,reducedMotionConfig:i,visualState:o},s={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.scheduleRender=()=>_t.render(this.render,!1,!0);const{latestValues:a,renderState:l}=o;this.latestValues=a,this.baseTarget={...a},this.initialValues=n.initial?{...a}:{},this.renderState=l,this.parent=t,this.props=n,this.presenceContext=r,this.depth=t?t.depth+1:0,this.reducedMotionConfig=i,this.options=s,this.isControllingVariants=r1(n),this.isVariantNode=bD(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:u,...c}=this.scrapeMotionValuesFromProps(n,{});for(const d in c){const f=c[d];a[d]!==void 0&&_r(f)&&(f.set(a[d],!1),dy(u)&&u.add(d))}}scrapeMotionValuesFromProps(t,n){return{}}mount(t){this.current=t,ZP.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,r)=>this.bindToMotionValue(r,n)),ML.current||Ebe(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:q2.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){ZP.delete(this.current),this.projection&&this.projection.unmount(),Uo(this.notifyUpdate),Uo(this.render),this.valueSubscriptions.forEach(t=>t()),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const t in this.events)this.events[t].clear();for(const t in this.features)this.features[t].unmount();this.current=null}bindToMotionValue(t,n){const r=El.has(t),i=n.on("change",s=>{this.latestValues[t]=s,this.props.onUpdate&&_t.update(this.notifyUpdate,!1,!0),r&&this.projection&&(this.projection.isTransformDirty=!0)}),o=n.on("renderRequest",this.scheduleRender);this.valueSubscriptions.set(t,()=>{i(),o()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}loadFeatures({children:t,...n},r,i,o){let s,a;for(let l=0;lthis.scheduleRender(),animationType:typeof u=="string"?u:"both",initialPromotionConfig:o,layoutScroll:f,layoutRoot:h})}return a}updateFeatures(){for(const t in this.features){const n=this.features[t];n.isMounted?n.update():(n.mount(),n.isMounted=!0)}}triggerBuild(){this.build(this.renderState,this.latestValues,this.options,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):Wt()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}makeTargetAnimatable(t,n=!0){return this.makeTargetAnimatableFromInstance(t,this.props,n)}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let r=0;rn.variantChildren.delete(t)}addValue(t,n){n!==this.values.get(t)&&(this.removeValue(t),this.bindToMotionValue(t,n)),this.values.set(t,n),this.latestValues[t]=n.get()}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let r=this.values.get(t);return r===void 0&&n!==void 0&&(r=uc(n,{owner:this}),this.addValue(t,r)),r}readValue(t){var n;return this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:(n=this.getBaseTargetFromProps(this.props,t))!==null&&n!==void 0?n:this.readValueFromInstance(this.current,t,this.options)}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){var n;const{initial:r}=this.props,i=typeof r=="string"||typeof r=="object"?(n=JC(this.props,r))===null||n===void 0?void 0:n[t]:void 0;if(r&&i!==void 0)return i;const o=this.getBaseTargetFromProps(this.props,t);return o!==void 0&&!_r(o)?o:this.initialValues[t]!==void 0&&i===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new l3),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}}class DL extends Obe{sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:r}){delete n[t],delete r[t]}makeTargetAnimatableFromInstance({transition:t,transitionEnd:n,...r},{transformValues:i},o){let s=Xve(r,t||{},this);if(i&&(n&&(n=i(n)),r&&(r=i(r)),s&&(s=i(s))),o){Wve(this,r,s);const a=Tbe(this,r,s,n);n=a.transitionEnd,r=a.target}return{transition:t,transitionEnd:n,...r}}}function Rbe(e){return window.getComputedStyle(e)}class Ibe extends DL{readValueFromInstance(t,n){if(El.has(n)){const r=i3(n);return r&&r.default||0}else{const r=Rbe(t),i=(xD(n)?r.getPropertyValue(n):r[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:n}){return CL(t,n)}build(t,n,r,i){WC(t,n,r,i.transformTemplate)}scrapeMotionValuesFromProps(t,n){return ZC(t,n)}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;_r(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}renderInstance(t,n,r,i){kD(t,n,r,i)}}class Mbe extends DL{constructor(){super(...arguments),this.isSVGTag=!1}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(El.has(n)){const r=i3(n);return r&&r.default||0}return n=OD.has(n)?n:QC(n),t.getAttribute(n)}measureInstanceViewportBox(){return Wt()}scrapeMotionValuesFromProps(t,n){return ID(t,n)}build(t,n,r,i){XC(t,n,r,this.isSVGTag,i.transformTemplate)}renderInstance(t,n,r,i){RD(t,n,r,i)}mount(t){this.isSVGTag=YC(t.tagName),super.mount(t)}}const Nbe=(e,t)=>qC(e)?new Mbe(t,{enableHardwareAcceleration:!1}):new Ibe(t,{enableHardwareAcceleration:!0}),Dbe={layout:{ProjectionNode:RL,MeasureLayout:TL}},Lbe={...u1e,...O0e,...hbe,...Dbe},$be=Bye((e,t)=>p0e(e,t,Lbe,Nbe));function LL(){const e=k.useRef(!1);return iy(()=>(e.current=!0,()=>{e.current=!1}),[]),e}function Fbe(){const e=LL(),[t,n]=k.useState(0),r=k.useCallback(()=>{e.current&&n(t+1)},[t]);return[k.useCallback(()=>_t.postRender(r),[r]),t]}class Bbe extends k.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(n&&t.isPresent&&!this.props.isPresent){const r=this.props.sizeRef.current;r.height=n.offsetHeight||0,r.width=n.offsetWidth||0,r.top=n.offsetTop,r.left=n.offsetLeft}return null}componentDidUpdate(){}render(){return this.props.children}}function jbe({children:e,isPresent:t}){const n=k.useId(),r=k.useRef(null),i=k.useRef({width:0,height:0,top:0,left:0});return k.useInsertionEffect(()=>{const{width:o,height:s,top:a,left:l}=i.current;if(t||!r.current||!o||!s)return;r.current.dataset.motionPopId=n;const u=document.createElement("style");return document.head.appendChild(u),u.sheet&&u.sheet.insertRule(` + [data-motion-pop-id="${n}"] { + position: absolute !important; + width: ${o}px !important; + height: ${s}px !important; + top: ${a}px !important; + left: ${l}px !important; + } + `),()=>{document.head.removeChild(u)}},[t]),k.createElement(Bbe,{isPresent:t,childRef:r,sizeRef:i},k.cloneElement(e,{ref:r}))}const gS=({children:e,initial:t,isPresent:n,onExitComplete:r,custom:i,presenceAffectsLayout:o,mode:s})=>{const a=MD(Vbe),l=k.useId(),u=k.useMemo(()=>({id:l,initial:t,isPresent:n,custom:i,onExitComplete:c=>{a.set(c,!0);for(const d of a.values())if(!d)return;r&&r()},register:c=>(a.set(c,!1),()=>a.delete(c))}),o?void 0:[n]);return k.useMemo(()=>{a.forEach((c,d)=>a.set(d,!1))},[n]),k.useEffect(()=>{!n&&!a.size&&r&&r()},[n]),s==="popLayout"&&(e=k.createElement(jbe,{isPresent:n},e)),k.createElement(Lh.Provider,{value:u},e)};function Vbe(){return new Map}function zbe(e){return k.useEffect(()=>()=>e(),[])}const Ql=e=>e.key||"";function Ube(e,t){e.forEach(n=>{const r=Ql(n);t.set(r,n)})}function Gbe(e){const t=[];return k.Children.forEach(e,n=>{k.isValidElement(n)&&t.push(n)}),t}const Hbe=({children:e,custom:t,initial:n=!0,onExitComplete:r,exitBeforeEnter:i,presenceAffectsLayout:o=!0,mode:s="sync"})=>{const a=k.useContext(HC).forceRender||Fbe()[0],l=LL(),u=Gbe(e);let c=u;const d=k.useRef(new Map).current,f=k.useRef(c),h=k.useRef(new Map).current,p=k.useRef(!0);if(iy(()=>{p.current=!1,Ube(u,h),f.current=c}),zbe(()=>{p.current=!0,h.clear(),d.clear()}),p.current)return k.createElement(k.Fragment,null,c.map(y=>k.createElement(gS,{key:Ql(y),isPresent:!0,initial:n?void 0:!1,presenceAffectsLayout:o,mode:s},y)));c=[...c];const m=f.current.map(Ql),S=u.map(Ql),v=m.length;for(let y=0;y{if(S.indexOf(g)!==-1)return;const b=h.get(g);if(!b)return;const _=m.indexOf(g);let w=y;if(!w){const x=()=>{h.delete(g),d.delete(g);const T=f.current.findIndex(P=>P.key===g);if(f.current.splice(T,1),!d.size){if(f.current=u,l.current===!1)return;a(),r&&r()}};w=k.createElement(gS,{key:Ql(b),isPresent:!1,onExitComplete:x,custom:t,presenceAffectsLayout:o,mode:s},b),d.set(g,w)}c.splice(_,0,w)}),c=c.map(y=>{const g=y.key;return d.has(g)?y:k.createElement(gS,{key:Ql(y),isPresent:!0,presenceAffectsLayout:o,mode:s},y)}),k.createElement(k.Fragment,null,d.size?c:c.map(y=>k.cloneElement(y)))};var qbe=Ige({"0%":{transform:"rotate(0deg)"},"100%":{transform:"rotate(360deg)"}}),$L=Tl((e,t)=>{const n=mD("Spinner",e),{label:r="Loading...",thickness:i="2px",speed:o="0.45s",emptyColor:s="transparent",className:a,...l}=fD(e),u=oD("chakra-spinner",a),c={display:"inline-block",borderColor:"currentColor",borderStyle:"solid",borderRadius:"99999px",borderWidth:i,borderBottomColor:s,borderLeftColor:s,animation:`${qbe} ${o} linear infinite`,...n};return K.jsx(sl.div,{ref:t,__css:c,className:u,...l,children:r&&K.jsx(sl.span,{srOnly:!0,children:r})})});$L.displayName="Spinner";var W2=Tl(function(t,n){const{htmlWidth:r,htmlHeight:i,alt:o,...s}=t;return K.jsx("img",{width:r,height:i,ref:n,alt:o,...s})});W2.displayName="NativeImage";function Wbe(e){const{loading:t,src:n,srcSet:r,onLoad:i,onError:o,crossOrigin:s,sizes:a,ignoreFallback:l}=e,[u,c]=k.useState("pending");k.useEffect(()=>{c(n?"loading":"pending")},[n]);const d=k.useRef(),f=k.useCallback(()=>{if(!n)return;h();const p=new Image;p.src=n,s&&(p.crossOrigin=s),r&&(p.srcset=r),a&&(p.sizes=a),t&&(p.loading=t),p.onload=m=>{h(),c("loaded"),i==null||i(m)},p.onerror=m=>{h(),c("failed"),o==null||o(m)},d.current=p},[n,s,r,a,i,o,t]),h=()=>{d.current&&(d.current.onload=null,d.current.onerror=null,d.current=null)};return Mge(()=>{if(!l)return u==="loading"&&f(),()=>{h()}},[u,f,l]),l?"loaded":u}var Kbe=(e,t)=>e!=="loaded"&&t==="beforeLoadOrError"||e==="failed"&&t==="onError";function Xbe(e,t=[]){const n=Object.assign({},e);for(const r of t)r in n&&delete n[r];return n}var u3=Tl(function(t,n){const{fallbackSrc:r,fallback:i,src:o,srcSet:s,align:a,fit:l,loading:u,ignoreFallback:c,crossOrigin:d,fallbackStrategy:f="beforeLoadOrError",referrerPolicy:h,...p}=t,m=r!==void 0||i!==void 0,S=u!=null||c||!m,v=Wbe({...t,crossOrigin:d,ignoreFallback:S}),y=Kbe(v,f),g={ref:n,objectFit:l,objectPosition:a,...S?p:Xbe(p,["onError","onLoad"])};return y?i||K.jsx(sl.img,{as:W2,className:"chakra-image__placeholder",src:r,...g}):K.jsx(sl.img,{as:W2,src:o,srcSet:s,crossOrigin:d,loading:u,referrerPolicy:h,className:"chakra-image",...g})});u3.displayName="Image";var Ybe=rye?k.useLayoutEffect:k.useEffect;function e8(e,t=[]){const n=k.useRef(e);return Ybe(()=>{n.current=e}),k.useCallback((...r)=>{var i;return(i=n.current)==null?void 0:i.call(n,...r)},t)}function Qbe(e,t){const n=k.useId();return k.useMemo(()=>e||[t,n].filter(Boolean).join("-"),[e,t,n])}function Zbe(e,t){const n=e!==void 0;return[n,n&&typeof e<"u"?e:t]}function Jbe(e={}){const{onClose:t,onOpen:n,isOpen:r,id:i}=e,o=e8(n),s=e8(t),[a,l]=k.useState(e.defaultIsOpen||!1),[u,c]=Zbe(r,a),d=Qbe(i,"disclosure"),f=k.useCallback(()=>{u||l(!1),s==null||s()},[u,s]),h=k.useCallback(()=>{u||l(!0),o==null||o()},[u,o]),p=k.useCallback(()=>{(c?f:h)()},[c,h,f]);return{isOpen:!!c,onOpen:h,onClose:f,onToggle:p,isControlled:u,getButtonProps:(m={})=>({...m,"aria-expanded":c,"aria-controls":d,onClick:cye(m.onClick,p)}),getDisclosureProps:(m={})=>({...m,hidden:!c,id:d})}}var K2=Tl(function(t,n){const r=mD("Heading",t),{className:i,...o}=fD(t);return K.jsx(sl.h2,{ref:n,className:oD("chakra-heading",t.className),...o,__css:r})});K2.displayName="Heading";var c3=sl("div");c3.displayName="Box";var FL=Tl(function(t,n){const{size:r,centerContent:i=!0,...o}=t,s=i?{display:"flex",alignItems:"center",justifyContent:"center"}:{};return K.jsx(c3,{ref:n,boxSize:r,__css:{...s,flexShrink:0,flexGrow:0},...o})});FL.displayName="Square";var eSe=Tl(function(t,n){const{size:r,...i}=t;return K.jsx(FL,{size:r,ref:n,borderRadius:"9999px",...i})});eSe.displayName="Circle";var d3=Tl(function(t,n){const{direction:r,align:i,justify:o,wrap:s,basis:a,grow:l,shrink:u,...c}=t,d={display:"flex",flexDirection:r,alignItems:i,justifyContent:o,flexWrap:s,flexBasis:a,flexGrow:l,flexShrink:u};return K.jsx(sl.div,{ref:n,__css:d,...c})});d3.displayName="Flex";const tSe=""+new URL("logo-13003d72.png",import.meta.url).href,nSe=()=>K.jsxs(d3,{position:"relative",width:"100vw",height:"100vh",alignItems:"center",justifyContent:"center",bg:"#151519",children:[K.jsx(u3,{src:tSe,w:"8rem",h:"8rem"}),K.jsx($L,{label:"Loading",color:"grey",position:"absolute",size:"sm",width:"24px !important",height:"24px !important",right:"1.5rem",bottom:"1.5rem"})]}),rSe=k.memo(nSe);function X2(e){"@babel/helpers - typeof";return X2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},X2(e)}var BL=[],iSe=BL.forEach,oSe=BL.slice;function Y2(e){return iSe.call(oSe.call(arguments,1),function(t){if(t)for(var n in t)e[n]===void 0&&(e[n]=t[n])}),e}function jL(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":X2(XMLHttpRequest))==="object"}function sSe(e){return!!e&&typeof e.then=="function"}function aSe(e){return sSe(e)?e:Promise.resolve(e)}function lSe(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Q2={exports:{}},Wp={exports:{}},t8;function uSe(){return t8||(t8=1,function(e,t){var n=typeof self<"u"?self:Ee,r=function(){function o(){this.fetch=!1,this.DOMException=n.DOMException}return o.prototype=n,new o}();(function(o){(function(s){var a={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function l(C){return C&&DataView.prototype.isPrototypeOf(C)}if(a.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(C){return C&&u.indexOf(Object.prototype.toString.call(C))>-1};function d(C){if(typeof C!="string"&&(C=String(C)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(C))throw new TypeError("Invalid character in header field name");return C.toLowerCase()}function f(C){return typeof C!="string"&&(C=String(C)),C}function h(C){var O={next:function(){var I=C.shift();return{done:I===void 0,value:I}}};return a.iterable&&(O[Symbol.iterator]=function(){return O}),O}function p(C){this.map={},C instanceof p?C.forEach(function(O,I){this.append(I,O)},this):Array.isArray(C)?C.forEach(function(O){this.append(O[0],O[1])},this):C&&Object.getOwnPropertyNames(C).forEach(function(O){this.append(O,C[O])},this)}p.prototype.append=function(C,O){C=d(C),O=f(O);var I=this.map[C];this.map[C]=I?I+", "+O:O},p.prototype.delete=function(C){delete this.map[d(C)]},p.prototype.get=function(C){return C=d(C),this.has(C)?this.map[C]:null},p.prototype.has=function(C){return this.map.hasOwnProperty(d(C))},p.prototype.set=function(C,O){this.map[d(C)]=f(O)},p.prototype.forEach=function(C,O){for(var I in this.map)this.map.hasOwnProperty(I)&&C.call(O,this.map[I],I,this)},p.prototype.keys=function(){var C=[];return this.forEach(function(O,I){C.push(I)}),h(C)},p.prototype.values=function(){var C=[];return this.forEach(function(O){C.push(O)}),h(C)},p.prototype.entries=function(){var C=[];return this.forEach(function(O,I){C.push([I,O])}),h(C)},a.iterable&&(p.prototype[Symbol.iterator]=p.prototype.entries);function m(C){if(C.bodyUsed)return Promise.reject(new TypeError("Already read"));C.bodyUsed=!0}function S(C){return new Promise(function(O,I){C.onload=function(){O(C.result)},C.onerror=function(){I(C.error)}})}function v(C){var O=new FileReader,I=S(O);return O.readAsArrayBuffer(C),I}function y(C){var O=new FileReader,I=S(O);return O.readAsText(C),I}function g(C){for(var O=new Uint8Array(C),I=new Array(O.length),N=0;N-1?O:C}function T(C,O){O=O||{};var I=O.body;if(C instanceof T){if(C.bodyUsed)throw new TypeError("Already read");this.url=C.url,this.credentials=C.credentials,O.headers||(this.headers=new p(C.headers)),this.method=C.method,this.mode=C.mode,this.signal=C.signal,!I&&C._bodyInit!=null&&(I=C._bodyInit,C.bodyUsed=!0)}else this.url=String(C);if(this.credentials=O.credentials||this.credentials||"same-origin",(O.headers||!this.headers)&&(this.headers=new p(O.headers)),this.method=x(O.method||this.method||"GET"),this.mode=O.mode||this.mode||null,this.signal=O.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&I)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(I)}T.prototype.clone=function(){return new T(this,{body:this._bodyInit})};function P(C){var O=new FormData;return C.trim().split("&").forEach(function(I){if(I){var N=I.split("="),R=N.shift().replace(/\+/g," "),D=N.join("=").replace(/\+/g," ");O.append(decodeURIComponent(R),decodeURIComponent(D))}}),O}function E(C){var O=new p,I=C.replace(/\r?\n[\t ]+/g," ");return I.split(/\r?\n/).forEach(function(N){var R=N.split(":"),D=R.shift().trim();if(D){var L=R.join(":").trim();O.append(D,L)}}),O}_.call(T.prototype);function A(C,O){O||(O={}),this.type="default",this.status=O.status===void 0?200:O.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in O?O.statusText:"OK",this.headers=new p(O.headers),this.url=O.url||"",this._initBody(C)}_.call(A.prototype),A.prototype.clone=function(){return new A(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},A.error=function(){var C=new A(null,{status:0,statusText:""});return C.type="error",C};var $=[301,302,303,307,308];A.redirect=function(C,O){if($.indexOf(O)===-1)throw new RangeError("Invalid status code");return new A(null,{status:O,headers:{location:C}})},s.DOMException=o.DOMException;try{new s.DOMException}catch{s.DOMException=function(O,I){this.message=O,this.name=I;var N=Error(O);this.stack=N.stack},s.DOMException.prototype=Object.create(Error.prototype),s.DOMException.prototype.constructor=s.DOMException}function M(C,O){return new Promise(function(I,N){var R=new T(C,O);if(R.signal&&R.signal.aborted)return N(new s.DOMException("Aborted","AbortError"));var D=new XMLHttpRequest;function L(){D.abort()}D.onload=function(){var j={status:D.status,statusText:D.statusText,headers:E(D.getAllResponseHeaders()||"")};j.url="responseURL"in D?D.responseURL:j.headers.get("X-Request-URL");var U="response"in D?D.response:D.responseText;I(new A(U,j))},D.onerror=function(){N(new TypeError("Network request failed"))},D.ontimeout=function(){N(new TypeError("Network request failed"))},D.onabort=function(){N(new s.DOMException("Aborted","AbortError"))},D.open(R.method,R.url,!0),R.credentials==="include"?D.withCredentials=!0:R.credentials==="omit"&&(D.withCredentials=!1),"responseType"in D&&a.blob&&(D.responseType="blob"),R.headers.forEach(function(j,U){D.setRequestHeader(U,j)}),R.signal&&(R.signal.addEventListener("abort",L),D.onreadystatechange=function(){D.readyState===4&&R.signal.removeEventListener("abort",L)}),D.send(typeof R._bodyInit>"u"?null:R._bodyInit)})}return M.polyfill=!0,o.fetch||(o.fetch=M,o.Headers=p,o.Request=T,o.Response=A),s.Headers=p,s.Request=T,s.Response=A,s.fetch=M,Object.defineProperty(s,"__esModule",{value:!0}),s})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=r;t=i.fetch,t.default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t}(Wp,Wp.exports)),Wp.exports}(function(e,t){var n;if(typeof fetch=="function"&&(typeof Ee<"u"&&Ee.fetch?n=Ee.fetch:typeof window<"u"&&window.fetch?n=window.fetch:n=fetch),typeof lSe<"u"&&(typeof window>"u"||typeof window.document>"u")){var r=n||uSe();r.default&&(r=r.default),t.default=r,e.exports=t.default}})(Q2,Q2.exports);var VL=Q2.exports;const zL=al(VL),n8=O8({__proto__:null,default:zL},[VL]);function hy(e){"@babel/helpers - typeof";return hy=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},hy(e)}var Do;typeof fetch=="function"&&(typeof global<"u"&&global.fetch?Do=global.fetch:typeof window<"u"&&window.fetch?Do=window.fetch:Do=fetch);var Wf;jL()&&(typeof global<"u"&&global.XMLHttpRequest?Wf=global.XMLHttpRequest:typeof window<"u"&&window.XMLHttpRequest&&(Wf=window.XMLHttpRequest));var py;typeof ActiveXObject=="function"&&(typeof global<"u"&&global.ActiveXObject?py=global.ActiveXObject:typeof window<"u"&&window.ActiveXObject&&(py=window.ActiveXObject));!Do&&n8&&!Wf&&!py&&(Do=zL||n8);typeof Do!="function"&&(Do=void 0);var Z2=function(t,n){if(n&&hy(n)==="object"){var r="";for(var i in n)r+="&"+encodeURIComponent(i)+"="+encodeURIComponent(n[i]);if(!r)return t;t=t+(t.indexOf("?")!==-1?"&":"?")+r.slice(1)}return t},r8=function(t,n,r){Do(t,n).then(function(i){if(!i.ok)return r(i.statusText||"Error",{status:i.status});i.text().then(function(o){r(null,{status:i.status,data:o})}).catch(r)}).catch(r)},i8=!1,cSe=function(t,n,r,i){t.queryStringParams&&(n=Z2(n,t.queryStringParams));var o=Y2({},typeof t.customHeaders=="function"?t.customHeaders():t.customHeaders);r&&(o["Content-Type"]="application/json");var s=typeof t.requestOptions=="function"?t.requestOptions(r):t.requestOptions,a=Y2({method:r?"POST":"GET",body:r?t.stringify(r):void 0,headers:o},i8?{}:s);try{r8(n,a,i)}catch(l){if(!s||Object.keys(s).length===0||!l.message||l.message.indexOf("not implemented")<0)return i(l);try{Object.keys(s).forEach(function(u){delete a[u]}),r8(n,a,i),i8=!0}catch(u){i(u)}}},dSe=function(t,n,r,i){r&&hy(r)==="object"&&(r=Z2("",r).slice(1)),t.queryStringParams&&(n=Z2(n,t.queryStringParams));try{var o;Wf?o=new Wf:o=new py("MSXML2.XMLHTTP.3.0"),o.open(r?"POST":"GET",n,1),t.crossDomain||o.setRequestHeader("X-Requested-With","XMLHttpRequest"),o.withCredentials=!!t.withCredentials,r&&o.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),o.overrideMimeType&&o.overrideMimeType("application/json");var s=t.customHeaders;if(s=typeof s=="function"?s():s,s)for(var a in s)o.setRequestHeader(a,s[a]);o.onreadystatechange=function(){o.readyState>3&&i(o.status>=400?o.statusText:null,{status:o.status,data:o.responseText})},o.send(r)}catch(l){console&&console.log(l)}},fSe=function(t,n,r,i){if(typeof r=="function"&&(i=r,r=void 0),i=i||function(){},Do&&n.indexOf("file:")!==0)return cSe(t,n,r,i);if(jL()||typeof ActiveXObject=="function")return dSe(t,n,r,i);i(new Error("No fetch and no xhr implementation found!"))};function Kf(e){"@babel/helpers - typeof";return Kf=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Kf(e)}function hSe(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o8(e,t){for(var n=0;n1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};hSe(this,e),this.services=t,this.options=n,this.allOptions=r,this.type="backend",this.init(t,n,r)}return pSe(e,[{key:"init",value:function(n){var r=this,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=n,this.options=Y2(i,this.options||{},ySe()),this.allOptions=o,this.services&&this.options.reloadInterval&&setInterval(function(){return r.reload()},this.options.reloadInterval)}},{key:"readMulti",value:function(n,r,i){this._readAny(n,n,r,r,i)}},{key:"read",value:function(n,r,i){this._readAny([n],n,[r],r,i)}},{key:"_readAny",value:function(n,r,i,o,s){var a=this,l=this.options.loadPath;typeof this.options.loadPath=="function"&&(l=this.options.loadPath(n,i)),l=aSe(l),l.then(function(u){if(!u)return s(null,{});var c=a.services.interpolator.interpolate(u,{lng:n.join("+"),ns:i.join("+")});a.loadUrl(c,s,r,o)})}},{key:"loadUrl",value:function(n,r,i,o){var s=this,a=typeof i=="string"?[i]:i,l=typeof o=="string"?[o]:o,u=this.options.parseLoadPayload(a,l);this.options.request(this.options,n,u,function(c,d){if(d&&(d.status>=500&&d.status<600||!d.status))return r("failed loading "+n+"; status code: "+d.status,!0);if(d&&d.status>=400&&d.status<500)return r("failed loading "+n+"; status code: "+d.status,!1);if(!d&&c&&c.message&&c.message.indexOf("Failed to fetch")>-1)return r("failed loading "+n+": "+c.message,!0);if(c)return r(c,!1);var f,h;try{typeof d.data=="string"?f=s.options.parse(d.data,i,o):f=d.data}catch{h="failed parsing "+n+" to json"}if(h)return r(h,!1);r(null,f)})}},{key:"create",value:function(n,r,i,o,s){var a=this;if(this.options.addPath){typeof n=="string"&&(n=[n]);var l=this.options.parsePayload(r,i,o),u=0,c=[],d=[];n.forEach(function(f){var h=a.options.addPath;typeof a.options.addPath=="function"&&(h=a.options.addPath(f,r));var p=a.services.interpolator.interpolate(h,{lng:f,ns:r});a.options.request(a.options,p,l,function(m,S){u+=1,c.push(m),d.push(S),u===n.length&&typeof s=="function"&&s(c,d)})})}}},{key:"reload",value:function(){var n=this,r=this.services,i=r.backendConnector,o=r.languageUtils,s=r.logger,a=i.language;if(!(a&&a.toLowerCase()==="cimode")){var l=[],u=function(d){var f=o.toResolveHierarchy(d);f.forEach(function(h){l.indexOf(h)<0&&l.push(h)})};u(a),this.allOptions.preload&&this.allOptions.preload.forEach(function(c){return u(c)}),l.forEach(function(c){n.allOptions.ns.forEach(function(d){i.read(c,d,"read",null,null,function(f,h){f&&s.warn("loading namespace ".concat(d," for language ").concat(c," failed"),f),!f&&h&&s.log("loaded namespace ".concat(d," for language ").concat(c),h),i.loaded("".concat(c,"|").concat(d),f,h)})})})}}}]),e}();GL.type="backend";const vSe=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,bSe={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},SSe=e=>bSe[e],_Se=e=>e.replace(vSe,SSe);let J2={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:_Se};function wSe(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};J2={...J2,...e}}function E4e(){return J2}let HL;function xSe(e){HL=e}function P4e(){return HL}const CSe={type:"3rdParty",init(e){wSe(e.options.react),xSe(e)}};zn.use(GL).use(CSe).init({fallbackLng:"en",debug:!1,backend:{loadPath:"/locales/{{lng}}.json"},interpolation:{escapeValue:!1},returnNull:!1});const TSe=e=>{const{socket:t,storeApi:n}=e,{dispatch:r,getState:i}=n;t.on("connect",()=>{fe("socketio").debug("Connected"),r(n7());const{sessionId:s}=i().system;s&&(t.emit("subscribe",{session:s}),r(Vx({sessionId:s})))}),t.on("connect_error",o=>{o&&o.message&&o.data==="ERR_UNAUTHENTICATED"&&r(Ft(Ga({title:o.message,status:"error",duration:1e4})))}),t.on("disconnect",()=>{r(i7())}),t.on("invocation_started",o=>{r(u7({data:o}))}),t.on("generator_progress",o=>{r(g7({data:o}))}),t.on("invocation_error",o=>{r(f7({data:o}))}),t.on("invocation_complete",o=>{r(zx({data:o}))}),t.on("graph_execution_state_complete",o=>{r(h7({data:o}))}),t.on("model_load_started",o=>{r(y7({data:o}))}),t.on("model_load_completed",o=>{r(v7({data:o}))}),t.on("session_retrieval_error",o=>{r(b7({data:o}))}),t.on("invocation_retrieval_error",o=>{r(_7({data:o}))})},ro=Object.create(null);ro.open="0";ro.close="1";ro.ping="2";ro.pong="3";ro.message="4";ro.upgrade="5";ro.noop="6";const Ag=Object.create(null);Object.keys(ro).forEach(e=>{Ag[ro[e]]=e});const ESe={type:"error",data:"parser error"},qL=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",WL=typeof ArrayBuffer=="function",KL=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,f3=({type:e,data:t},n,r)=>qL&&t instanceof Blob?n?r(t):s8(t,r):WL&&(t instanceof ArrayBuffer||KL(t))?n?r(t):s8(new Blob([t]),r):r(ro[e]+(t||"")),s8=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function a8(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let mS;function PSe(e,t){if(qL&&e.data instanceof Blob)return e.data.arrayBuffer().then(a8).then(t);if(WL&&(e.data instanceof ArrayBuffer||KL(e.data)))return t(a8(e.data));f3(e,!1,n=>{mS||(mS=new TextEncoder),t(mS.encode(n))})}const l8="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",md=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,i=0,o,s,a,l;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const u=new ArrayBuffer(t),c=new Uint8Array(u);for(r=0;r>4,c[i++]=(s&15)<<4|a>>2,c[i++]=(a&3)<<6|l&63;return u},kSe=typeof ArrayBuffer=="function",h3=(e,t)=>{if(typeof e!="string")return{type:"message",data:XL(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:OSe(e.substring(1),t)}:Ag[n]?e.length>1?{type:Ag[n],data:e.substring(1)}:{type:Ag[n]}:ESe},OSe=(e,t)=>{if(kSe){const n=ASe(e);return XL(n,t)}else return{base64:!0,data:e}},XL=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},YL=String.fromCharCode(30),RSe=(e,t)=>{const n=e.length,r=new Array(n);let i=0;e.forEach((o,s)=>{f3(o,!1,a=>{r[s]=a,++i===n&&t(r.join(YL))})})},ISe=(e,t)=>{const n=e.split(YL),r=[];for(let i=0;i54;return h3(r?e:yS.decode(e),n)}const QL=4;function Zt(e){if(e)return NSe(e)}function NSe(e){for(var t in Zt.prototype)e[t]=Zt.prototype[t];return e}Zt.prototype.on=Zt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Zt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};Zt.prototype.off=Zt.prototype.removeListener=Zt.prototype.removeAllListeners=Zt.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,i=0;itypeof self<"u"?self:typeof window<"u"?window:Function("return this")())();function ZL(e,...t){return t.reduce((n,r)=>(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const DSe=qr.setTimeout,LSe=qr.clearTimeout;function a1(e,t){t.useNativeTimers?(e.setTimeoutFn=DSe.bind(qr),e.clearTimeoutFn=LSe.bind(qr)):(e.setTimeoutFn=qr.setTimeout.bind(qr),e.clearTimeoutFn=qr.clearTimeout.bind(qr))}const $Se=1.33;function FSe(e){return typeof e=="string"?BSe(e):Math.ceil((e.byteLength||e.size)*$Se)}function BSe(e){let t=0,n=0;for(let r=0,i=e.length;r=57344?n+=3:(r++,n+=4);return n}function jSe(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VSe(e){let t={},n=e.split("&");for(let r=0,i=n.length;r0);return t}function e$(){const e=d8(+new Date);return e!==c8?(u8=0,c8=e):e+"."+d8(u8++)}for(;Kp{this.readyState="paused",t()};if(this.polling||!this.writable){let r=0;this.polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};ISe(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,RSe(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=e$()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}request(t={}){return Object.assign(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new $u(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(i,o)=>{this.onError("xhr post error",i,o)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}let $u=class kg extends Zt{constructor(t,n){super(),a1(this,n),this.opts=n,this.method=n.method||"GET",this.uri=t,this.data=n.data!==void 0?n.data:null,this.create()}create(){var t;const n=ZL(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new n$(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let i in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(i)&&r.setRequestHeader(i,this.opts.extraHeaders[i])}}catch{}if(this.method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this.opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var i;r.readyState===3&&((i=this.opts.cookieJar)===null||i===void 0||i.parseCookies(r)),r.readyState===4&&(r.status===200||r.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof r.status=="number"?r.status:0)},0))},r.send(this.data)}catch(i){this.setTimeoutFn(()=>{this.onError(i)},0);return}typeof document<"u"&&(this.index=kg.requestsCount++,kg.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=HSe,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete kg.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}};$u.requestsCount=0;$u.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",f8);else if(typeof addEventListener=="function"){const e="onpagehide"in qr?"pagehide":"unload";addEventListener(e,f8,!1)}}function f8(){for(let e in $u.requests)$u.requests.hasOwnProperty(e)&&$u.requests[e].abort()}const g3=(()=>typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0))(),Xp=qr.WebSocket||qr.MozWebSocket,h8=!0,KSe="arraybuffer",p8=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class XSe extends p3{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),n=this.opts.protocols,r=p8?{}:ZL(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=h8&&!p8?n?new Xp(t,n):new Xp(t):new Xp(t,n,r)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType||KSe,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n{const s={};try{h8&&this.ws.send(o)}catch{}i&&g3(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=e$()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!Xp}}function YSe(e,t){return e.type==="message"&&typeof e.data!="string"&&t[0]>=48&&t[0]<=54}class QSe extends p3{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(t=>{const n=t.readable.getReader();this.writer=t.writable.getWriter();let r;const i=()=>{n.read().then(({done:s,value:a})=>{s||(!r&&a.byteLength===1&&a[0]===54?r=!0:(this.onPacket(MSe(a,r,"arraybuffer")),r=!1),i())}).catch(s=>{})};i();const o=this.query.sid?`0{"sid":"${this.query.sid}"}`:"0";this.writer.write(new TextEncoder().encode(o)).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{YSe(r,o)&&this.writer.write(Uint8Array.of(54)),this.writer.write(o).then(()=>{i&&g3(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const ZSe={websocket:XSe,webtransport:QSe,polling:WSe},JSe=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,e_e=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function tw(e){const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let i=JSe.exec(e||""),o={},s=14;for(;s--;)o[e_e[s]]=i[s]||"";return n!=-1&&r!=-1&&(o.source=t,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=t_e(o,o.path),o.queryKey=n_e(o,o.query),o}function t_e(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function n_e(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,i,o){i&&(n[i]=o)}),n}let r$=class Zl extends Zt{constructor(t,n={}){super(),this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=tw(t),n.hostname=t.host,n.secure=t.protocol==="https"||t.protocol==="wss",n.port=t.port,t.query&&(n.query=t.query)):n.host&&(n.hostname=tw(n.host).host),a1(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=n.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=VSe(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=QL,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new ZSe[t](r)}open(){let t;if(this.opts.rememberUpgrade&&Zl.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else t=this.transports[0];this.readyState="opening";try{t=this.createTransport(t)}catch{this.transports.shift(),this.open();return}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",n=>this.onClose("transport close",n))}probe(t){let n=this.createTransport(t),r=!1;Zl.priorWebsocketSuccess=!1;const i=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",d=>{if(!r)if(d.type==="pong"&&d.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;Zl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(c(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const f=new Error("probe error");f.transport=n.name,this.emitReserved("upgradeError",f)}}))};function o(){r||(r=!0,c(),n.close(),n=null)}const s=d=>{const f=new Error("probe error: "+d);f.transport=n.name,o(),this.emitReserved("upgradeError",f)};function a(){s("transport closed")}function l(){s("socket closed")}function u(d){n&&d.name!==n.name&&o()}const c=()=>{n.removeListener("open",i),n.removeListener("error",s),n.removeListener("close",a),this.off("close",l),this.off("upgrading",u)};n.once("open",i),n.once("error",s),n.once("close",a),this.once("close",l),this.once("upgrading",u),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",Zl.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let t=0;const n=this.upgrades.length;for(;t{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r0&&n>this.maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}write(t,n,r){return this.sendPacket("message",t,n,r),this}send(t,n,r){return this.sendPacket("message",t,n,r),this}sendPacket(t,n,r,i){if(typeof n=="function"&&(i=n,n=void 0),typeof r=="function"&&(i=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const o={type:t,data:n,options:r};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}onError(t){Zl.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,n){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const n=[];let r=0;const i=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,i$=Object.prototype.toString,s_e=typeof Blob=="function"||typeof Blob<"u"&&i$.call(Blob)==="[object BlobConstructor]",a_e=typeof File=="function"||typeof File<"u"&&i$.call(File)==="[object FileConstructor]";function m3(e){return i_e&&(e instanceof ArrayBuffer||o_e(e))||s_e&&e instanceof Blob||a_e&&e instanceof File}function Og(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n=0&&e.num{delete this.acks[t];for(let s=0;s{this.io.clearTimeoutFn(o),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((i,o)=>{n.push((s,a)=>r?s?o(s):i(a):i(s)),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((i,...o)=>r!==this._queue[0]?void 0:(i!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(i)):(this._queue.shift(),n&&n(null,...o)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:Me.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case Me.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Me.EVENT:case Me.BINARY_EVENT:this.onevent(t);break;case Me.ACK:case Me.BINARY_ACK:this.onack(t);break;case Me.DISCONNECT:this.ondisconnect();break;case Me.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...i){r||(r=!0,n.packet({type:Me.ACK,id:t,data:i}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(n.apply(this,t.data),delete this.acks[t.id])}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Me.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r0&&e.jitter<=1?e.jitter:0,this.attempts=0}Tc.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};Tc.prototype.reset=function(){this.attempts=0};Tc.prototype.setMin=function(e){this.ms=e};Tc.prototype.setMax=function(e){this.max=e};Tc.prototype.setJitter=function(e){this.jitter=e};class iw extends Zt{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,a1(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Tc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const i=n.parser||p_e;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new r$(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=ui(n,"open",function(){r.onopen(),t&&t()}),o=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),t?t(a):this.maybeReconnectOnOpen()},s=ui(n,"error",o);if(this._timeout!==!1){const a=this._timeout,l=this.setTimeoutFn(()=>{i(),o(new Error("timeout")),n.close()},a);this.opts.autoUnref&&l.unref(),this.subs.push(()=>{this.clearTimeoutFn(l)})}return this.subs.push(i),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(ui(t,"ping",this.onping.bind(this)),ui(t,"data",this.ondata.bind(this)),ui(t,"error",this.onerror.bind(this)),ui(t,"close",this.onclose.bind(this)),ui(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){g3(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new o$(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;rt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,n){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(i=>{i?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",i)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const sd={};function Rg(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=r_e(e,t.path||"/socket.io"),r=n.source,i=n.id,o=n.path,s=sd[i]&&o in sd[i].nsps,a=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let l;return a?l=new iw(r,t):(sd[i]||(sd[i]=new iw(r,t)),l=sd[i]),n.query&&!t.query&&(t.query=n.queryKey),l.socket(n.path,t)}Object.assign(Rg,{Manager:iw,Socket:o$,io:Rg,connect:Rg});const m8=()=>{let e=!1,t=`ws://${window.location.host}`;const n={timeout:6e4,path:"/ws/socket.io",autoConnect:!1};if(["nodes","package"].includes("production")){const o=Tf.get();o&&(t=o.replace(/^https?\:\/\//i,""));const s=Cf.get();s&&(n.auth={token:s}),n.transports=["websocket","polling"]}const r=Rg(t,n);return o=>s=>a=>{const{dispatch:l,getState:u}=o;if(e||(TSe({storeApi:o,socket:r}),e=!0,r.connect()),On.fulfilled.match(a)){const c=a.payload.id,d=u().system.sessionId;d&&(r.emit("unsubscribe",{session:d}),l(a7({sessionId:d}))),r.emit("subscribe",{session:c}),l(Vx({sessionId:c}))}s(a)}},l1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Ec(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function v3(e){return"nodeType"in e}function or(e){var t,n;return e?Ec(e)?e:v3(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function b3(e){const{Document:t}=or(e);return e instanceof t}function Vh(e){return Ec(e)?!1:e instanceof or(e).HTMLElement}function m_e(e){return e instanceof or(e).SVGElement}function Pc(e){return e?Ec(e)?e.document:v3(e)?b3(e)?e:Vh(e)?e.ownerDocument:document:document:document}const io=l1?k.useLayoutEffect:k.useEffect;function u1(e){const t=k.useRef(e);return io(()=>{t.current=e}),k.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i{e.current=setInterval(r,i)},[]),n=k.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function Xf(e,t){t===void 0&&(t=[e]);const n=k.useRef(e);return io(()=>{n.current!==e&&(n.current=e)},t),n}function zh(e,t){const n=k.useRef();return k.useMemo(()=>{const r=e(n.current);return n.current=r,r},[...t])}function gy(e){const t=u1(e),n=k.useRef(null),r=k.useCallback(i=>{i!==n.current&&(t==null||t(i,n.current)),n.current=i},[]);return[n,r]}function my(e){const t=k.useRef();return k.useEffect(()=>{t.current=e},[e]),t.current}let vS={};function c1(e,t){return k.useMemo(()=>{if(t)return t;const n=vS[e]==null?0:vS[e]+1;return vS[e]=n,e+"-"+n},[e,t])}function s$(e){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i{const a=Object.entries(s);for(const[l,u]of a){const c=o[l];c!=null&&(o[l]=c+e*u)}return o},{...t})}}const Fu=s$(1),yy=s$(-1);function v_e(e){return"clientX"in e&&"clientY"in e}function S3(e){if(!e)return!1;const{KeyboardEvent:t}=or(e.target);return t&&e instanceof t}function b_e(e){if(!e)return!1;const{TouchEvent:t}=or(e.target);return t&&e instanceof t}function Yf(e){if(b_e(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return v_e(e)?{x:e.clientX,y:e.clientY}:null}const Qf=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[Qf.Translate.toString(e),Qf.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+" "+n+"ms "+r}}}),y8="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function S_e(e){return e.matches(y8)?e:e.querySelector(y8)}const __e={display:"none"};function w_e(e){let{id:t,value:n}=e;return We.createElement("div",{id:t,style:__e},n)}const x_e={position:"fixed",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};function C_e(e){let{id:t,announcement:n}=e;return We.createElement("div",{id:t,style:x_e,role:"status","aria-live":"assertive","aria-atomic":!0},n)}function T_e(){const[e,t]=k.useState("");return{announce:k.useCallback(r=>{r!=null&&t(r)},[]),announcement:e}}const a$=k.createContext(null);function E_e(e){const t=k.useContext(a$);k.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(e)},[e,t])}function P_e(){const[e]=k.useState(()=>new Set),t=k.useCallback(r=>(e.add(r),()=>e.delete(r)),[e]);return[k.useCallback(r=>{let{type:i,event:o}=r;e.forEach(s=>{var a;return(a=s[i])==null?void 0:a.call(s,o)})},[e]),t]}const A_e={draggable:` + To pick up a draggable item, press the space bar. + While dragging, use the arrow keys to move the item. + Press space again to drop the item in its new position, or press escape to cancel. + `},k_e={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function O_e(e){let{announcements:t=k_e,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=A_e}=e;const{announce:o,announcement:s}=T_e(),a=c1("DndLiveRegion"),[l,u]=k.useState(!1);if(k.useEffect(()=>{u(!0)},[]),E_e(k.useMemo(()=>({onDragStart(d){let{active:f}=d;o(t.onDragStart({active:f}))},onDragMove(d){let{active:f,over:h}=d;t.onDragMove&&o(t.onDragMove({active:f,over:h}))},onDragOver(d){let{active:f,over:h}=d;o(t.onDragOver({active:f,over:h}))},onDragEnd(d){let{active:f,over:h}=d;o(t.onDragEnd({active:f,over:h}))},onDragCancel(d){let{active:f,over:h}=d;o(t.onDragCancel({active:f,over:h}))}}),[o,t])),!l)return null;const c=We.createElement(We.Fragment,null,We.createElement(w_e,{id:r,value:i.draggable}),We.createElement(C_e,{id:a,announcement:s}));return n?zi.createPortal(c,n):c}var nn;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(nn||(nn={}));function vy(){}function v8(e,t){return k.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function R_e(){for(var e=arguments.length,t=new Array(e),n=0;n[...t].filter(r=>r!=null),[...t])}const Ei=Object.freeze({x:0,y:0});function I_e(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function M_e(e,t){const n=Yf(e);if(!n)return"0 0";const r={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return r.x+"% "+r.y+"%"}function N_e(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return n-r}function D_e(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return r-n}function L_e(e){let{left:t,top:n,height:r,width:i}=e;return[{x:t,y:n},{x:t+i,y:n},{x:t,y:n+r},{x:t+i,y:n+r}]}function $_e(e,t){if(!e||e.length===0)return null;const[n]=e;return t?n[t]:n}function F_e(e,t){const n=Math.max(t.top,e.top),r=Math.max(t.left,e.left),i=Math.min(t.left+t.width,e.left+e.width),o=Math.min(t.top+t.height,e.top+e.height),s=i-r,a=o-n;if(r{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const i=[];for(const o of r){const{id:s}=o,a=n.get(s);if(a){const l=F_e(a,t);l>0&&i.push({id:s,data:{droppableContainer:o,value:l}})}}return i.sort(D_e)};function j_e(e,t){const{top:n,left:r,bottom:i,right:o}=t;return n<=e.y&&e.y<=i&&r<=e.x&&e.x<=o}const V_e=e=>{let{droppableContainers:t,droppableRects:n,pointerCoordinates:r}=e;if(!r)return[];const i=[];for(const o of t){const{id:s}=o,a=n.get(s);if(a&&j_e(r,a)){const u=L_e(a).reduce((d,f)=>d+I_e(r,f),0),c=Number((u/4).toFixed(4));i.push({id:s,data:{droppableContainer:o,value:c}})}}return i.sort(N_e)};function z_e(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function l$(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Ei}function U_e(e){return function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),o=1;o({...s,top:s.top+e*a.y,bottom:s.bottom+e*a.y,left:s.left+e*a.x,right:s.right+e*a.x}),{...n})}}const G_e=U_e(1);function u$(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function H_e(e,t,n){const r=u$(t);if(!r)return e;const{scaleX:i,scaleY:o,x:s,y:a}=r,l=e.left-s-(1-i)*parseFloat(n),u=e.top-a-(1-o)*parseFloat(n.slice(n.indexOf(" ")+1)),c=i?e.width/i:e.width,d=o?e.height/o:e.height;return{width:c,height:d,top:u,right:l+c,bottom:u+d,left:l}}const q_e={ignoreTransform:!1};function Uh(e,t){t===void 0&&(t=q_e);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:u,transformOrigin:c}=or(e).getComputedStyle(e);u&&(n=H_e(n,u,c))}const{top:r,left:i,width:o,height:s,bottom:a,right:l}=n;return{top:r,left:i,width:o,height:s,bottom:a,right:l}}function b8(e){return Uh(e,{ignoreTransform:!0})}function W_e(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function K_e(e,t){return t===void 0&&(t=or(e).getComputedStyle(e)),t.position==="fixed"}function X_e(e,t){t===void 0&&(t=or(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const o=t[i];return typeof o=="string"?n.test(o):!1})}function _3(e,t){const n=[];function r(i){if(t!=null&&n.length>=t||!i)return n;if(b3(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!Vh(i)||m_e(i)||n.includes(i))return n;const o=or(e).getComputedStyle(i);return i!==e&&X_e(i,o)&&n.push(i),K_e(i,o)?n:r(i.parentNode)}return e?r(e):n}function c$(e){const[t]=_3(e,1);return t??null}function bS(e){return!l1||!e?null:Ec(e)?e:v3(e)?b3(e)||e===Pc(e).scrollingElement?window:Vh(e)?e:null:null}function d$(e){return Ec(e)?e.scrollX:e.scrollLeft}function f$(e){return Ec(e)?e.scrollY:e.scrollTop}function ow(e){return{x:d$(e),y:f$(e)}}var hn;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(hn||(hn={}));function h$(e){return!l1||!e?!1:e===document.scrollingElement}function p$(e){const t={x:0,y:0},n=h$(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},i=e.scrollTop<=t.y,o=e.scrollLeft<=t.x,s=e.scrollTop>=r.y,a=e.scrollLeft>=r.x;return{isTop:i,isLeft:o,isBottom:s,isRight:a,maxScroll:r,minScroll:t}}const Y_e={x:.2,y:.2};function Q_e(e,t,n,r,i){let{top:o,left:s,right:a,bottom:l}=n;r===void 0&&(r=10),i===void 0&&(i=Y_e);const{isTop:u,isBottom:c,isLeft:d,isRight:f}=p$(e),h={x:0,y:0},p={x:0,y:0},m={height:t.height*i.y,width:t.width*i.x};return!u&&o<=t.top+m.height?(h.y=hn.Backward,p.y=r*Math.abs((t.top+m.height-o)/m.height)):!c&&l>=t.bottom-m.height&&(h.y=hn.Forward,p.y=r*Math.abs((t.bottom-m.height-l)/m.height)),!f&&a>=t.right-m.width?(h.x=hn.Forward,p.x=r*Math.abs((t.right-m.width-a)/m.width)):!d&&s<=t.left+m.width&&(h.x=hn.Backward,p.x=r*Math.abs((t.left+m.width-s)/m.width)),{direction:h,speed:p}}function Z_e(e){if(e===document.scrollingElement){const{innerWidth:o,innerHeight:s}=window;return{top:0,left:0,right:o,bottom:s,width:o,height:s}}const{top:t,left:n,right:r,bottom:i}=e.getBoundingClientRect();return{top:t,left:n,right:r,bottom:i,width:e.clientWidth,height:e.clientHeight}}function g$(e){return e.reduce((t,n)=>Fu(t,ow(n)),Ei)}function J_e(e){return e.reduce((t,n)=>t+d$(n),0)}function e2e(e){return e.reduce((t,n)=>t+f$(n),0)}function m$(e,t){if(t===void 0&&(t=Uh),!e)return;const{top:n,left:r,bottom:i,right:o}=t(e);c$(e)&&(i<=0||o<=0||n>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const t2e=[["x",["left","right"],J_e],["y",["top","bottom"],e2e]];class w3{constructor(t,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=_3(n),i=g$(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[o,s,a]of t2e)for(const l of s)Object.defineProperty(this,l,{get:()=>{const u=a(r),c=i[o]-u;return this.rect[l]+c},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Dd{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=t}add(t,n,r){var i;(i=this.target)==null||i.addEventListener(t,n,r),this.listeners.push([t,n,r])}}function n2e(e){const{EventTarget:t}=or(e);return e instanceof t?e:Pc(e)}function SS(e,t){const n=Math.abs(e.x),r=Math.abs(e.y);return typeof t=="number"?Math.sqrt(n**2+r**2)>t:"x"in t&&"y"in t?n>t.x&&r>t.y:"x"in t?n>t.x:"y"in t?r>t.y:!1}var Ur;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Ur||(Ur={}));function S8(e){e.preventDefault()}function r2e(e){e.stopPropagation()}var st;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter"})(st||(st={}));const y$={start:[st.Space,st.Enter],cancel:[st.Esc],end:[st.Space,st.Enter]},i2e=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case st.Right:return{...n,x:n.x+25};case st.Left:return{...n,x:n.x-25};case st.Down:return{...n,y:n.y+25};case st.Up:return{...n,y:n.y-25}}};class v${constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:n}}=t;this.props=t,this.listeners=new Dd(Pc(n)),this.windowListeners=new Dd(or(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Ur.Resize,this.handleCancel),this.windowListeners.add(Ur.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Ur.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&m$(r),n(Ei)}handleKeyDown(t){if(S3(t)){const{active:n,context:r,options:i}=this.props,{keyboardCodes:o=y$,coordinateGetter:s=i2e,scrollBehavior:a="smooth"}=i,{code:l}=t;if(o.end.includes(l)){this.handleEnd(t);return}if(o.cancel.includes(l)){this.handleCancel(t);return}const{collisionRect:u}=r.current,c=u?{x:u.left,y:u.top}:Ei;this.referenceCoordinates||(this.referenceCoordinates=c);const d=s(t,{active:n,context:r.current,currentCoordinates:c});if(d){const f=yy(d,c),h={x:0,y:0},{scrollableAncestors:p}=r.current;for(const m of p){const S=t.code,{isTop:v,isRight:y,isLeft:g,isBottom:b,maxScroll:_,minScroll:w}=p$(m),x=Z_e(m),T={x:Math.min(S===st.Right?x.right-x.width/2:x.right,Math.max(S===st.Right?x.left:x.left+x.width/2,d.x)),y:Math.min(S===st.Down?x.bottom-x.height/2:x.bottom,Math.max(S===st.Down?x.top:x.top+x.height/2,d.y))},P=S===st.Right&&!y||S===st.Left&&!g,E=S===st.Down&&!b||S===st.Up&&!v;if(P&&T.x!==d.x){const A=m.scrollLeft+f.x,$=S===st.Right&&A<=_.x||S===st.Left&&A>=w.x;if($&&!f.y){m.scrollTo({left:A,behavior:a});return}$?h.x=m.scrollLeft-A:h.x=S===st.Right?m.scrollLeft-_.x:m.scrollLeft-w.x,h.x&&m.scrollBy({left:-h.x,behavior:a});break}else if(E&&T.y!==d.y){const A=m.scrollTop+f.y,$=S===st.Down&&A<=_.y||S===st.Up&&A>=w.y;if($&&!f.x){m.scrollTo({top:A,behavior:a});return}$?h.y=m.scrollTop-A:h.y=S===st.Down?m.scrollTop-_.y:m.scrollTop-w.y,h.y&&m.scrollBy({top:-h.y,behavior:a});break}}this.handleMove(t,Fu(yy(d,this.referenceCoordinates),h))}}}handleMove(t,n){const{onMove:r}=this.props;t.preventDefault(),r(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}v$.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:r=y$,onActivation:i}=t,{active:o}=n;const{code:s}=e.nativeEvent;if(r.start.includes(s)){const a=o.activatorNode.current;return a&&e.target!==a?!1:(e.preventDefault(),i==null||i({event:e.nativeEvent}),!0)}return!1}}];function _8(e){return!!(e&&"distance"in e)}function w8(e){return!!(e&&"delay"in e)}class x3{constructor(t,n,r){var i;r===void 0&&(r=n2e(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=n;const{event:o}=t,{target:s}=o;this.props=t,this.events=n,this.document=Pc(s),this.documentListeners=new Dd(this.document),this.listeners=new Dd(r),this.windowListeners=new Dd(or(s)),this.initialCoordinates=(i=Yf(o))!=null?i:Ei,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:n}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),this.windowListeners.add(Ur.Resize,this.handleCancel),this.windowListeners.add(Ur.DragStart,S8),this.windowListeners.add(Ur.VisibilityChange,this.handleCancel),this.windowListeners.add(Ur.ContextMenu,S8),this.documentListeners.add(Ur.Keydown,this.handleKeydown),n){if(_8(n))return;if(w8(n)){this.timeoutId=setTimeout(this.handleStart,n.delay);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(Ur.Click,r2e,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Ur.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:r,initialCoordinates:i,props:o}=this,{onMove:s,options:{activationConstraint:a}}=o;if(!i)return;const l=(n=Yf(t))!=null?n:Ei,u=yy(i,l);if(!r&&a){if(w8(a))return SS(u,a.tolerance)?this.handleCancel():void 0;if(_8(a))return a.tolerance!=null&&SS(u,a.tolerance)?this.handleCancel():SS(u,a.distance)?this.handleStart():void 0}t.cancelable&&t.preventDefault(),s(l)}handleEnd(){const{onEnd:t}=this.props;this.detach(),t()}handleCancel(){const{onCancel:t}=this.props;this.detach(),t()}handleKeydown(t){t.code===st.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const o2e={move:{name:"pointermove"},end:{name:"pointerup"}};class b$ extends x3{constructor(t){const{event:n}=t,r=Pc(n.target);super(t,o2e,r)}}b$.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return!n.isPrimary||n.button!==0?!1:(r==null||r({event:n}),!0)}}];const s2e={move:{name:"mousemove"},end:{name:"mouseup"}};var sw;(function(e){e[e.RightClick=2]="RightClick"})(sw||(sw={}));class S$ extends x3{constructor(t){super(t,s2e,Pc(t.event.target))}}S$.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return n.button===sw.RightClick?!1:(r==null||r({event:n}),!0)}}];const _S={move:{name:"touchmove"},end:{name:"touchend"}};class _$ extends x3{constructor(t){super(t,_S)}static setup(){return window.addEventListener(_S.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(_S.move.name,t)};function t(){}}}_$.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;const{touches:i}=n;return i.length>1?!1:(r==null||r({event:n}),!0)}}];var Ld;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(Ld||(Ld={}));var by;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(by||(by={}));function a2e(e){let{acceleration:t,activator:n=Ld.Pointer,canScroll:r,draggingRect:i,enabled:o,interval:s=5,order:a=by.TreeOrder,pointerCoordinates:l,scrollableAncestors:u,scrollableAncestorRects:c,delta:d,threshold:f}=e;const h=u2e({delta:d,disabled:!o}),[p,m]=y_e(),S=k.useRef({x:0,y:0}),v=k.useRef({x:0,y:0}),y=k.useMemo(()=>{switch(n){case Ld.Pointer:return l?{top:l.y,bottom:l.y,left:l.x,right:l.x}:null;case Ld.DraggableRect:return i}},[n,i,l]),g=k.useRef(null),b=k.useCallback(()=>{const w=g.current;if(!w)return;const x=S.current.x*v.current.x,T=S.current.y*v.current.y;w.scrollBy(x,T)},[]),_=k.useMemo(()=>a===by.TreeOrder?[...u].reverse():u,[a,u]);k.useEffect(()=>{if(!o||!u.length||!y){m();return}for(const w of _){if((r==null?void 0:r(w))===!1)continue;const x=u.indexOf(w),T=c[x];if(!T)continue;const{direction:P,speed:E}=Q_e(w,T,y,t,f);for(const A of["x","y"])h[A][P[A]]||(E[A]=0,P[A]=0);if(E.x>0||E.y>0){m(),g.current=w,p(b,s),S.current=E,v.current=P;return}}S.current={x:0,y:0},v.current={x:0,y:0},m()},[t,b,r,m,o,s,JSON.stringify(y),JSON.stringify(h),p,u,_,c,JSON.stringify(f)])}const l2e={x:{[hn.Backward]:!1,[hn.Forward]:!1},y:{[hn.Backward]:!1,[hn.Forward]:!1}};function u2e(e){let{delta:t,disabled:n}=e;const r=my(t);return zh(i=>{if(n||!r||!i)return l2e;const o={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[hn.Backward]:i.x[hn.Backward]||o.x===-1,[hn.Forward]:i.x[hn.Forward]||o.x===1},y:{[hn.Backward]:i.y[hn.Backward]||o.y===-1,[hn.Forward]:i.y[hn.Forward]||o.y===1}}},[n,t,r])}function c2e(e,t){const n=t!==null?e.get(t):void 0,r=n?n.node.current:null;return zh(i=>{var o;return t===null?null:(o=r??i)!=null?o:null},[r,t])}function d2e(e,t){return k.useMemo(()=>e.reduce((n,r)=>{const{sensor:i}=r,o=i.activators.map(s=>({eventName:s.eventName,handler:t(s.handler,r)}));return[...n,...o]},[]),[e,t])}var Zf;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Zf||(Zf={}));var aw;(function(e){e.Optimized="optimized"})(aw||(aw={}));const x8=new Map;function f2e(e,t){let{dragging:n,dependencies:r,config:i}=t;const[o,s]=k.useState(null),{frequency:a,measure:l,strategy:u}=i,c=k.useRef(e),d=S(),f=Xf(d),h=k.useCallback(function(v){v===void 0&&(v=[]),!f.current&&s(y=>y===null?v:y.concat(v.filter(g=>!y.includes(g))))},[f]),p=k.useRef(null),m=zh(v=>{if(d&&!n)return x8;if(!v||v===x8||c.current!==e||o!=null){const y=new Map;for(let g of e){if(!g)continue;if(o&&o.length>0&&!o.includes(g.id)&&g.rect.current){y.set(g.id,g.rect.current);continue}const b=g.node.current,_=b?new w3(l(b),b):null;g.rect.current=_,_&&y.set(g.id,_)}return y}return v},[e,o,n,d,l]);return k.useEffect(()=>{c.current=e},[e]),k.useEffect(()=>{d||h()},[n,d]),k.useEffect(()=>{o&&o.length>0&&s(null)},[JSON.stringify(o)]),k.useEffect(()=>{d||typeof a!="number"||p.current!==null||(p.current=setTimeout(()=>{h(),p.current=null},a))},[a,d,h,...r]),{droppableRects:m,measureDroppableContainers:h,measuringScheduled:o!=null};function S(){switch(u){case Zf.Always:return!1;case Zf.BeforeDragging:return n;default:return!n}}}function C3(e,t){return zh(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function h2e(e,t){return C3(e,t)}function p2e(e){let{callback:t,disabled:n}=e;const r=u1(t),i=k.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:o}=window;return new o(r)},[r,n]);return k.useEffect(()=>()=>i==null?void 0:i.disconnect(),[i]),i}function d1(e){let{callback:t,disabled:n}=e;const r=u1(t),i=k.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:o}=window;return new o(r)},[n]);return k.useEffect(()=>()=>i==null?void 0:i.disconnect(),[i]),i}function g2e(e){return new w3(Uh(e),e)}function C8(e,t,n){t===void 0&&(t=g2e);const[r,i]=k.useReducer(a,null),o=p2e({callback(l){if(e)for(const u of l){const{type:c,target:d}=u;if(c==="childList"&&d instanceof HTMLElement&&d.contains(e)){i();break}}}}),s=d1({callback:i});return io(()=>{i(),e?(s==null||s.observe(e),o==null||o.observe(document.body,{childList:!0,subtree:!0})):(s==null||s.disconnect(),o==null||o.disconnect())},[e]),r;function a(l){if(!e)return null;if(e.isConnected===!1){var u;return(u=l??n)!=null?u:null}const c=t(e);return JSON.stringify(l)===JSON.stringify(c)?l:c}}function m2e(e){const t=C3(e);return l$(e,t)}const T8=[];function y2e(e){const t=k.useRef(e),n=zh(r=>e?r&&r!==T8&&e&&t.current&&e.parentNode===t.current.parentNode?r:_3(e):T8,[e]);return k.useEffect(()=>{t.current=e},[e]),n}function v2e(e){const[t,n]=k.useState(null),r=k.useRef(e),i=k.useCallback(o=>{const s=bS(o.target);s&&n(a=>a?(a.set(s,ow(s)),new Map(a)):null)},[]);return k.useEffect(()=>{const o=r.current;if(e!==o){s(o);const a=e.map(l=>{const u=bS(l);return u?(u.addEventListener("scroll",i,{passive:!0}),[u,ow(u)]):null}).filter(l=>l!=null);n(a.length?new Map(a):null),r.current=e}return()=>{s(e),s(o)};function s(a){a.forEach(l=>{const u=bS(l);u==null||u.removeEventListener("scroll",i)})}},[i,e]),k.useMemo(()=>e.length?t?Array.from(t.values()).reduce((o,s)=>Fu(o,s),Ei):g$(e):Ei,[e,t])}function E8(e,t){t===void 0&&(t=[]);const n=k.useRef(null);return k.useEffect(()=>{n.current=null},t),k.useEffect(()=>{const r=e!==Ei;r&&!n.current&&(n.current=e),!r&&n.current&&(n.current=null)},[e]),n.current?yy(e,n.current):Ei}function b2e(e){k.useEffect(()=>{if(!l1)return;const t=e.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of t)n==null||n()}},e.map(t=>{let{sensor:n}=t;return n}))}function S2e(e,t){return k.useMemo(()=>e.reduce((n,r)=>{let{eventName:i,handler:o}=r;return n[i]=s=>{o(s,t)},n},{}),[e,t])}function w$(e){return k.useMemo(()=>e?W_e(e):null,[e])}const wS=[];function _2e(e,t){t===void 0&&(t=Uh);const[n]=e,r=w$(n?or(n):null),[i,o]=k.useReducer(a,wS),s=d1({callback:o});return e.length>0&&i===wS&&o(),io(()=>{e.length?e.forEach(l=>s==null?void 0:s.observe(l)):(s==null||s.disconnect(),o())},[e]),i;function a(){return e.length?e.map(l=>h$(l)?r:new w3(t(l),l)):wS}}function x$(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return Vh(t)?t:e}function w2e(e){let{measure:t}=e;const[n,r]=k.useState(null),i=k.useCallback(u=>{for(const{target:c}of u)if(Vh(c)){r(d=>{const f=t(c);return d?{...d,width:f.width,height:f.height}:f});break}},[t]),o=d1({callback:i}),s=k.useCallback(u=>{const c=x$(u);o==null||o.disconnect(),c&&(o==null||o.observe(c)),r(c?t(c):null)},[t,o]),[a,l]=gy(s);return k.useMemo(()=>({nodeRef:a,rect:n,setRef:l}),[n,a,l])}const x2e=[{sensor:b$,options:{}},{sensor:v$,options:{}}],C2e={current:{}},Ig={draggable:{measure:b8},droppable:{measure:b8,strategy:Zf.WhileDragging,frequency:aw.Optimized},dragOverlay:{measure:Uh}};class $d extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,r;return(n=(r=this.get(t))==null?void 0:r.node.current)!=null?n:void 0}}const T2e={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new $d,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:vy},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Ig,measureDroppableContainers:vy,windowRect:null,measuringScheduled:!1},C$={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:vy,draggableNodes:new Map,over:null,measureDroppableContainers:vy},Gh=k.createContext(C$),T$=k.createContext(T2e);function E2e(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new $d}}}function P2e(e,t){switch(t.type){case nn.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case nn.DragMove:return e.draggable.active?{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}}:e;case nn.DragEnd:case nn.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case nn.RegisterDroppable:{const{element:n}=t,{id:r}=n,i=new $d(e.droppable.containers);return i.set(r,n),{...e,droppable:{...e.droppable,containers:i}}}case nn.SetDroppableDisabled:{const{id:n,key:r,disabled:i}=t,o=e.droppable.containers.get(n);if(!o||r!==o.key)return e;const s=new $d(e.droppable.containers);return s.set(n,{...o,disabled:i}),{...e,droppable:{...e.droppable,containers:s}}}case nn.UnregisterDroppable:{const{id:n,key:r}=t,i=e.droppable.containers.get(n);if(!i||r!==i.key)return e;const o=new $d(e.droppable.containers);return o.delete(n),{...e,droppable:{...e.droppable,containers:o}}}default:return e}}function A2e(e){let{disabled:t}=e;const{active:n,activatorEvent:r,draggableNodes:i}=k.useContext(Gh),o=my(r),s=my(n==null?void 0:n.id);return k.useEffect(()=>{if(!t&&!r&&o&&s!=null){if(!S3(o)||document.activeElement===o.target)return;const a=i.get(s);if(!a)return;const{activatorNode:l,node:u}=a;if(!l.current&&!u.current)return;requestAnimationFrame(()=>{for(const c of[l.current,u.current]){if(!c)continue;const d=S_e(c);if(d){d.focus();break}}})}},[r,t,i,s,o]),null}function E$(e,t){let{transform:n,...r}=t;return e!=null&&e.length?e.reduce((i,o)=>o({transform:i,...r}),n):n}function k2e(e){return k.useMemo(()=>({draggable:{...Ig.draggable,...e==null?void 0:e.draggable},droppable:{...Ig.droppable,...e==null?void 0:e.droppable},dragOverlay:{...Ig.dragOverlay,...e==null?void 0:e.dragOverlay}}),[e==null?void 0:e.draggable,e==null?void 0:e.droppable,e==null?void 0:e.dragOverlay])}function O2e(e){let{activeNode:t,measure:n,initialRect:r,config:i=!0}=e;const o=k.useRef(!1),{x:s,y:a}=typeof i=="boolean"?{x:i,y:i}:i;io(()=>{if(!s&&!a||!t){o.current=!1;return}if(o.current||!r)return;const u=t==null?void 0:t.node.current;if(!u||u.isConnected===!1)return;const c=n(u),d=l$(c,r);if(s||(d.x=0),a||(d.y=0),o.current=!0,Math.abs(d.x)>0||Math.abs(d.y)>0){const f=c$(u);f&&f.scrollBy({top:d.y,left:d.x})}},[t,s,a,r,n])}const f1=k.createContext({...Ei,scaleX:1,scaleY:1});var hs;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(hs||(hs={}));const R2e=k.memo(function(t){var n,r,i,o;let{id:s,accessibility:a,autoScroll:l=!0,children:u,sensors:c=x2e,collisionDetection:d=B_e,measuring:f,modifiers:h,...p}=t;const m=k.useReducer(P2e,void 0,E2e),[S,v]=m,[y,g]=P_e(),[b,_]=k.useState(hs.Uninitialized),w=b===hs.Initialized,{draggable:{active:x,nodes:T,translate:P},droppable:{containers:E}}=S,A=x?T.get(x):null,$=k.useRef({initial:null,translated:null}),M=k.useMemo(()=>{var Ct;return x!=null?{id:x,data:(Ct=A==null?void 0:A.data)!=null?Ct:C2e,rect:$}:null},[x,A]),C=k.useRef(null),[O,I]=k.useState(null),[N,R]=k.useState(null),D=Xf(p,Object.values(p)),L=c1("DndDescribedBy",s),j=k.useMemo(()=>E.getEnabled(),[E]),U=k2e(f),{droppableRects:G,measureDroppableContainers:W,measuringScheduled:X}=f2e(j,{dragging:w,dependencies:[P.x,P.y],config:U.droppable}),Y=c2e(T,x),B=k.useMemo(()=>N?Yf(N):null,[N]),H=da(),Q=h2e(Y,U.draggable.measure);O2e({activeNode:x?T.get(x):null,config:H.layoutShiftCompensation,initialRect:Q,measure:U.draggable.measure});const J=C8(Y,U.draggable.measure,Q),ne=C8(Y?Y.parentElement:null),te=k.useRef({activatorEvent:null,active:null,activeNode:Y,collisionRect:null,collisions:null,droppableRects:G,draggableNodes:T,draggingNode:null,draggingNodeRect:null,droppableContainers:E,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),xe=E.getNodeFor((n=te.current.over)==null?void 0:n.id),ve=w2e({measure:U.dragOverlay.measure}),ce=(r=ve.nodeRef.current)!=null?r:Y,Ne=w?(i=ve.rect)!=null?i:J:null,se=!!(ve.nodeRef.current&&ve.rect),gt=m2e(se?null:J),vn=w$(ce?or(ce):null),It=y2e(w?xe??Y:null),ut=_2e(It),Je=E$(h,{transform:{x:P.x-gt.x,y:P.y-gt.y,scaleX:1,scaleY:1},activatorEvent:N,active:M,activeNodeRect:J,containerNodeRect:ne,draggingNodeRect:Ne,over:te.current.over,overlayNodeRect:ve.rect,scrollableAncestors:It,scrollableAncestorRects:ut,windowRect:vn}),Gt=B?Fu(B,P):null,sr=v2e(It),ni=E8(sr),Lr=E8(sr,[J]),Rn=Fu(Je,ni),bn=Ne?G_e(Ne,Je):null,Un=M&&bn?d({active:M,collisionRect:bn,droppableRects:G,droppableContainers:j,pointerCoordinates:Gt}):null,Ht=$_e(Un,"id"),[xt,wr]=k.useState(null),$r=se?Je:Fu(Je,Lr),ri=z_e($r,(o=xt==null?void 0:xt.rect)!=null?o:null,J),uo=k.useCallback((Ct,et)=>{let{sensor:_n,options:ln}=et;if(C.current==null)return;const In=T.get(C.current);if(!In)return;const Gn=Ct.nativeEvent,ar=new _n({active:C.current,activeNode:In,event:Gn,options:ln,context:te,onStart(Hn){const wn=C.current;if(wn==null)return;const co=T.get(wn);if(!co)return;const{onDragStart:Zo}=D.current,Jo={active:{id:wn,data:co.data,rect:$}};zi.unstable_batchedUpdates(()=>{Zo==null||Zo(Jo),_(hs.Initializing),v({type:nn.DragStart,initialCoordinates:Hn,active:wn}),y({type:"onDragStart",event:Jo})})},onMove(Hn){v({type:nn.DragMove,coordinates:Hn})},onEnd:Oi(nn.DragEnd),onCancel:Oi(nn.DragCancel)});zi.unstable_batchedUpdates(()=>{I(ar),R(Ct.nativeEvent)});function Oi(Hn){return async function(){const{active:co,collisions:Zo,over:Jo,scrollAdjustedTranslate:Al}=te.current;let fo=null;if(co&&Al){const{cancelDrop:qn}=D.current;fo={activatorEvent:Gn,active:co,collisions:Zo,delta:Al,over:Jo},Hn===nn.DragEnd&&typeof qn=="function"&&await Promise.resolve(qn(fo))&&(Hn=nn.DragCancel)}C.current=null,zi.unstable_batchedUpdates(()=>{v({type:Hn}),_(hs.Uninitialized),wr(null),I(null),R(null);const qn=Hn===nn.DragEnd?"onDragEnd":"onDragCancel";if(fo){const fa=D.current[qn];fa==null||fa(fo),y({type:qn,event:fo})}})}}},[T]),Sn=k.useCallback((Ct,et)=>(_n,ln)=>{const In=_n.nativeEvent,Gn=T.get(ln);if(C.current!==null||!Gn||In.dndKit||In.defaultPrevented)return;const ar={active:Gn};Ct(_n,et.options,ar)===!0&&(In.dndKit={capturedBy:et.sensor},C.current=ln,uo(_n,et))},[T,uo]),ii=d2e(c,Sn);b2e(c),io(()=>{J&&b===hs.Initializing&&_(hs.Initialized)},[J,b]),k.useEffect(()=>{const{onDragMove:Ct}=D.current,{active:et,activatorEvent:_n,collisions:ln,over:In}=te.current;if(!et||!_n)return;const Gn={active:et,activatorEvent:_n,collisions:ln,delta:{x:Rn.x,y:Rn.y},over:In};zi.unstable_batchedUpdates(()=>{Ct==null||Ct(Gn),y({type:"onDragMove",event:Gn})})},[Rn.x,Rn.y]),k.useEffect(()=>{const{active:Ct,activatorEvent:et,collisions:_n,droppableContainers:ln,scrollAdjustedTranslate:In}=te.current;if(!Ct||C.current==null||!et||!In)return;const{onDragOver:Gn}=D.current,ar=ln.get(Ht),Oi=ar&&ar.rect.current?{id:ar.id,rect:ar.rect.current,data:ar.data,disabled:ar.disabled}:null,Hn={active:Ct,activatorEvent:et,collisions:_n,delta:{x:In.x,y:In.y},over:Oi};zi.unstable_batchedUpdates(()=>{wr(Oi),Gn==null||Gn(Hn),y({type:"onDragOver",event:Hn})})},[Ht]),io(()=>{te.current={activatorEvent:N,active:M,activeNode:Y,collisionRect:bn,collisions:Un,droppableRects:G,draggableNodes:T,draggingNode:ce,draggingNodeRect:Ne,droppableContainers:E,over:xt,scrollableAncestors:It,scrollAdjustedTranslate:Rn},$.current={initial:Ne,translated:bn}},[M,Y,Un,bn,T,ce,Ne,G,E,xt,It,Rn]),a2e({...H,delta:P,draggingRect:bn,pointerCoordinates:Gt,scrollableAncestors:It,scrollableAncestorRects:ut});const ca=k.useMemo(()=>({active:M,activeNode:Y,activeNodeRect:J,activatorEvent:N,collisions:Un,containerNodeRect:ne,dragOverlay:ve,draggableNodes:T,droppableContainers:E,droppableRects:G,over:xt,measureDroppableContainers:W,scrollableAncestors:It,scrollableAncestorRects:ut,measuringConfiguration:U,measuringScheduled:X,windowRect:vn}),[M,Y,J,N,Un,ne,ve,T,E,G,xt,W,It,ut,U,X,vn]),ki=k.useMemo(()=>({activatorEvent:N,activators:ii,active:M,activeNodeRect:J,ariaDescribedById:{draggable:L},dispatch:v,draggableNodes:T,over:xt,measureDroppableContainers:W}),[N,ii,M,J,v,L,T,xt,W]);return We.createElement(a$.Provider,{value:g},We.createElement(Gh.Provider,{value:ki},We.createElement(T$.Provider,{value:ca},We.createElement(f1.Provider,{value:ri},u)),We.createElement(A2e,{disabled:(a==null?void 0:a.restoreFocus)===!1})),We.createElement(O_e,{...a,hiddenTextDescribedById:L}));function da(){const Ct=(O==null?void 0:O.autoScrollEnabled)===!1,et=typeof l=="object"?l.enabled===!1:l===!1,_n=w&&!Ct&&!et;return typeof l=="object"?{...l,enabled:_n}:{enabled:_n}}}),I2e=k.createContext(null),P8="button",M2e="Droppable";function N2e(e){let{id:t,data:n,disabled:r=!1,attributes:i}=e;const o=c1(M2e),{activators:s,activatorEvent:a,active:l,activeNodeRect:u,ariaDescribedById:c,draggableNodes:d,over:f}=k.useContext(Gh),{role:h=P8,roleDescription:p="draggable",tabIndex:m=0}=i??{},S=(l==null?void 0:l.id)===t,v=k.useContext(S?f1:I2e),[y,g]=gy(),[b,_]=gy(),w=S2e(s,t),x=Xf(n);io(()=>(d.set(t,{id:t,key:o,node:y,activatorNode:b,data:x}),()=>{const P=d.get(t);P&&P.key===o&&d.delete(t)}),[d,t]);const T=k.useMemo(()=>({role:h,tabIndex:m,"aria-disabled":r,"aria-pressed":S&&h===P8?!0:void 0,"aria-roledescription":p,"aria-describedby":c.draggable}),[r,h,m,S,p,c.draggable]);return{active:l,activatorEvent:a,activeNodeRect:u,attributes:T,isDragging:S,listeners:r?void 0:w,node:y,over:f,setNodeRef:g,setActivatorNodeRef:_,transform:v}}function D2e(){return k.useContext(T$)}const L2e="Droppable",$2e={timeout:25};function F2e(e){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:i}=e;const o=c1(L2e),{active:s,dispatch:a,over:l,measureDroppableContainers:u}=k.useContext(Gh),c=k.useRef({disabled:n}),d=k.useRef(!1),f=k.useRef(null),h=k.useRef(null),{disabled:p,updateMeasurementsFor:m,timeout:S}={...$2e,...i},v=Xf(m??r),y=k.useCallback(()=>{if(!d.current){d.current=!0;return}h.current!=null&&clearTimeout(h.current),h.current=setTimeout(()=>{u(Array.isArray(v.current)?v.current:[v.current]),h.current=null},S)},[S]),g=d1({callback:y,disabled:p||!s}),b=k.useCallback((T,P)=>{g&&(P&&(g.unobserve(P),d.current=!1),T&&g.observe(T))},[g]),[_,w]=gy(b),x=Xf(t);return k.useEffect(()=>{!g||!_.current||(g.disconnect(),d.current=!1,g.observe(_.current))},[_,g]),io(()=>(a({type:nn.RegisterDroppable,element:{id:r,key:o,disabled:n,node:_,rect:f,data:x}}),()=>a({type:nn.UnregisterDroppable,key:o,id:r})),[r]),k.useEffect(()=>{n!==c.current.disabled&&(a({type:nn.SetDroppableDisabled,id:r,key:o,disabled:n}),c.current.disabled=n)},[r,o,n,a]),{active:s,rect:f,isOver:(l==null?void 0:l.id)===r,node:_,over:l,setNodeRef:w}}function B2e(e){let{animation:t,children:n}=e;const[r,i]=k.useState(null),[o,s]=k.useState(null),a=my(n);return!n&&!r&&a&&i(a),io(()=>{if(!o)return;const l=r==null?void 0:r.key,u=r==null?void 0:r.props.id;if(l==null||u==null){i(null);return}Promise.resolve(t(u,o)).then(()=>{i(null)})},[t,r,o]),We.createElement(We.Fragment,null,n,r?k.cloneElement(r,{ref:s}):null)}const j2e={x:0,y:0,scaleX:1,scaleY:1};function V2e(e){let{children:t}=e;return We.createElement(Gh.Provider,{value:C$},We.createElement(f1.Provider,{value:j2e},t))}const z2e={position:"fixed",touchAction:"none"},U2e=e=>S3(e)?"transform 250ms ease":void 0,G2e=k.forwardRef((e,t)=>{let{as:n,activatorEvent:r,adjustScale:i,children:o,className:s,rect:a,style:l,transform:u,transition:c=U2e}=e;if(!a)return null;const d=i?u:{...u,scaleX:1,scaleY:1},f={...z2e,width:a.width,height:a.height,top:a.top,left:a.left,transform:Qf.Transform.toString(d),transformOrigin:i&&r?M_e(r,a):void 0,transition:typeof c=="function"?c(r):c,...l};return We.createElement(n,{className:s,style:f,ref:t},o)}),H2e=e=>t=>{let{active:n,dragOverlay:r}=t;const i={},{styles:o,className:s}=e;if(o!=null&&o.active)for(const[a,l]of Object.entries(o.active))l!==void 0&&(i[a]=n.node.style.getPropertyValue(a),n.node.style.setProperty(a,l));if(o!=null&&o.dragOverlay)for(const[a,l]of Object.entries(o.dragOverlay))l!==void 0&&r.node.style.setProperty(a,l);return s!=null&&s.active&&n.node.classList.add(s.active),s!=null&&s.dragOverlay&&r.node.classList.add(s.dragOverlay),function(){for(const[l,u]of Object.entries(i))n.node.style.setProperty(l,u);s!=null&&s.active&&n.node.classList.remove(s.active)}},q2e=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:Qf.Transform.toString(t)},{transform:Qf.Transform.toString(n)}]},W2e={duration:250,easing:"ease",keyframes:q2e,sideEffects:H2e({styles:{active:{opacity:"0"}}})};function K2e(e){let{config:t,draggableNodes:n,droppableContainers:r,measuringConfiguration:i}=e;return u1((o,s)=>{if(t===null)return;const a=n.get(o);if(!a)return;const l=a.node.current;if(!l)return;const u=x$(s);if(!u)return;const{transform:c}=or(s).getComputedStyle(s),d=u$(c);if(!d)return;const f=typeof t=="function"?t:X2e(t);return m$(l,i.draggable.measure),f({active:{id:o,data:a.data,node:l,rect:i.draggable.measure(l)},draggableNodes:n,dragOverlay:{node:s,rect:i.dragOverlay.measure(u)},droppableContainers:r,measuringConfiguration:i,transform:d})})}function X2e(e){const{duration:t,easing:n,sideEffects:r,keyframes:i}={...W2e,...e};return o=>{let{active:s,dragOverlay:a,transform:l,...u}=o;if(!t)return;const c={x:a.rect.left-s.rect.left,y:a.rect.top-s.rect.top},d={scaleX:l.scaleX!==1?s.rect.width*l.scaleX/a.rect.width:1,scaleY:l.scaleY!==1?s.rect.height*l.scaleY/a.rect.height:1},f={x:l.x-c.x,y:l.y-c.y,...d},h=i({...u,active:s,dragOverlay:a,transform:{initial:l,final:f}}),[p]=h,m=h[h.length-1];if(JSON.stringify(p)===JSON.stringify(m))return;const S=r==null?void 0:r({active:s,dragOverlay:a,...u}),v=a.node.animate(h,{duration:t,easing:n,fill:"forwards"});return new Promise(y=>{v.onfinish=()=>{S==null||S(),y()}})}}let A8=0;function Y2e(e){return k.useMemo(()=>{if(e!=null)return A8++,A8},[e])}const Q2e=We.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:r,style:i,transition:o,modifiers:s,wrapperElement:a="div",className:l,zIndex:u=999}=e;const{activatorEvent:c,active:d,activeNodeRect:f,containerNodeRect:h,draggableNodes:p,droppableContainers:m,dragOverlay:S,over:v,measuringConfiguration:y,scrollableAncestors:g,scrollableAncestorRects:b,windowRect:_}=D2e(),w=k.useContext(f1),x=Y2e(d==null?void 0:d.id),T=E$(s,{activatorEvent:c,active:d,activeNodeRect:f,containerNodeRect:h,draggingNodeRect:S.rect,over:v,overlayNodeRect:S.rect,scrollableAncestors:g,scrollableAncestorRects:b,transform:w,windowRect:_}),P=C3(f),E=K2e({config:r,draggableNodes:p,droppableContainers:m,measuringConfiguration:y}),A=P?S.setRef:void 0;return We.createElement(V2e,null,We.createElement(B2e,{animation:E},d&&x?We.createElement(G2e,{key:x,id:d.id,ref:A,as:a,activatorEvent:c,adjustScale:t,className:l,transition:o,rect:P,style:{zIndex:u,...i},transform:T},n):null))}),Z2e=e=>{let{activatorEvent:t,draggingNodeRect:n,transform:r}=e;if(n&&t){const i=Yf(t);if(!i)return r;const o=i.x-n.left,s=i.y-n.top;return{...r,x:r.x+o-n.width/2,y:r.y+s-n.height/2}}return r},P$=()=>ak(),A4e=J9,Yp=28,k8={w:Yp,h:Yp,maxW:Yp,maxH:Yp,shadow:"dark-lg",borderRadius:"lg",opacity:.3,bg:"base.800",color:"base.50",_dark:{borderColor:"base.200",bg:"base.900",color:"base.100"}},J2e=e=>{if(!e.dragData)return null;if(e.dragData.payloadType==="IMAGE_DTO"){const{thumbnail_url:t,width:n,height:r}=e.dragData.payload.imageDTO;return K.jsx(c3,{sx:{position:"relative",width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",userSelect:"none",cursor:"none"},children:K.jsx(u3,{sx:{...k8},objectFit:"contain",src:t,width:n,height:r})})}return e.dragData.payloadType==="IMAGE_NAMES"?K.jsxs(d3,{sx:{cursor:"none",userSelect:"none",position:"relative",alignItems:"center",justifyContent:"center",flexDir:"column",...k8},children:[K.jsx(K2,{children:e.dragData.payload.image_names.length}),K.jsx(K2,{size:"sm",children:"Images"})]}):null},ewe=k.memo(J2e);function k4e(e){return F2e(e)}function O4e(e){return N2e(e)}const R4e=(e,t)=>{if(!e||!(t!=null&&t.data.current))return!1;const{actionType:n}=e,{payloadType:r}=t.data.current;if(e.id===t.data.current.id)return!1;switch(n){case"SET_CURRENT_IMAGE":return r==="IMAGE_DTO";case"SET_INITIAL_IMAGE":return r==="IMAGE_DTO";case"SET_CONTROLNET_IMAGE":return r==="IMAGE_DTO";case"SET_CANVAS_INITIAL_IMAGE":return r==="IMAGE_DTO";case"SET_NODES_IMAGE":return r==="IMAGE_DTO";case"SET_MULTI_NODES_IMAGE":return r==="IMAGE_DTO"||"IMAGE_NAMES";case"ADD_TO_BATCH":return r==="IMAGE_DTO"||"IMAGE_NAMES";case"MOVE_BOARD":{if(!(r==="IMAGE_DTO"||"IMAGE_NAMES"))return!1;if(r==="IMAGE_DTO"){const{imageDTO:o}=t.data.current.payload,s=o.board_id,a=e.context.boardId;return!(s===a)&&(s?!0:a)}return r!=="IMAGE_NAMES"}default:return!1}};function twe(e){return K.jsx(R2e,{...e})}const nwe=e=>{const[t,n]=k.useState(null),r=P$(),i=k.useCallback(u=>{console.log("dragStart",u.active.data.current);const c=u.active.data.current;c&&n(c)},[]),o=k.useCallback(u=>{var d;console.log("dragEnd",u.active.data.current);const c=(d=u.over)==null?void 0:d.data.current;!t||!c||(r(tN({overData:c,activeData:t})),n(null))},[t,r]),s=v8(S$,{activationConstraint:{distance:10}}),a=v8(_$,{activationConstraint:{distance:10}}),l=R_e(s,a);return K.jsxs(twe,{onDragStart:i,onDragEnd:o,sensors:l,collisionDetection:V_e,children:[e.children,K.jsx(Q2e,{dropAnimation:null,modifiers:[Z2e],children:K.jsx(Hbe,{children:t&&K.jsx($be.div,{layout:!0,initial:{opacity:0,scale:.7},animate:{opacity:1,scale:1,transition:{duration:.1}},children:K.jsx(ewe,{dragData:t})},"overlay-drag-image")})})]})},rwe=k.memo(nwe),iwe=k.createContext({isOpen:!1,onClose:()=>{},onClickAddToBoard:()=>{},handleAddToBoard:()=>{}}),owe=e=>{const[t,n]=k.useState(),{isOpen:r,onOpen:i,onClose:o}=Jbe(),s=P$(),a=k.useCallback(()=>{n(void 0),o()},[o]),l=k.useCallback(c=>{c&&(n(c),i())},[n,i]),u=k.useCallback(c=>{t&&(s(he.endpoints.addImageToBoard.initiate({imageDTO:t,board_id:c})),a())},[s,a,t]);return K.jsx(iwe.Provider,{value:{isOpen:r,image:t,onClose:a,onClickAddToBoard:l,handleAddToBoard:u},children:e.children})},swe=k.lazy(()=>G9(()=>import("./App-69e5ea36.js"),["./App-69e5ea36.js","./MantineProvider-8184f020.js","./App-6125620a.css"],import.meta.url)),awe=k.lazy(()=>G9(()=>import("./ThemeLocaleProvider-9ac72450.js"),["./ThemeLocaleProvider-9ac72450.js","./MantineProvider-8184f020.js","./ThemeLocaleProvider-5b992bc7.css"],import.meta.url)),lwe=({apiUrl:e,token:t,config:n,headerComponent:r,middleware:i})=>(k.useEffect(()=>(t&&Cf.set(t),e&&Tf.set(e),zM(),i&&i.length>0?c2(m8(),...i):c2(m8()),()=>{Tf.set(void 0),Cf.set(void 0)}),[e,t,i]),K.jsx(We.StrictMode,{children:K.jsx(mV,{store:Gpe,children:K.jsx(We.Suspense,{fallback:K.jsx(rSe,{}),children:K.jsx(awe,{children:K.jsx(rwe,{children:K.jsx(owe,{children:K.jsx(swe,{config:n,headerComponent:r})})})})})})})),uwe=k.memo(lwe);xS.createRoot(document.getElementById("root")).render(K.jsx(uwe,{}));export{fD as $,K as A,ti as B,Vt as C,Mu as D,Vn as E,fi as F,Xne as G,br as H,Is as I,$i as J,$3e as K,_I as L,cre as M,jre as N,ote as O,Zne as P,rc as Q,Tl as R,df as S,Nge as T,sl as U,oD as V,h4e as W,c4e as X,Hbe as Y,$be as Z,x4e as _,Zk as a,U_ as a$,$L as a0,mD as a1,d4e as a2,f4e as a3,Mge as a4,Ige as a5,p4e as a6,Na as a7,al as a8,rm as a9,d3 as aA,K2 as aB,o4e as aC,jN as aD,ZCe as aE,Y4 as aF,lCe as aG,zi as aH,BC as aI,nF as aJ,hwe as aK,dwe as aL,fwe as aM,Ee as aN,Ea as aO,C3e as aP,YM as aQ,w3e as aR,x3e as aS,S3e as aT,m3e as aU,Mpe as aV,k4e as aW,R4e as aX,b3e as aY,R3e as aZ,WCe as a_,IV as aa,We as ab,e8 as ac,uye as ad,w4e as ae,Io as af,rD as ag,R1e as ah,y4e as ai,R2 as aj,u4e as ak,_4e as al,Jn as am,mC as an,S0 as ao,A4e as ap,B3e as aq,Th as ar,nM as as,AM as at,Z0 as au,P$ as av,g5e as aw,Ft as ax,Ga as ay,c3 as az,Tx as b,I7 as b$,_3e as b0,u3 as b1,tSe as b2,vxe as b3,Ss as b4,A5e as b5,hp as b6,bge as b7,FC as b8,ZN as b9,ue as bA,iwe as bB,KCe as bC,dJ as bD,e3e as bE,$R as bF,Yxe as bG,RR as bH,G_ as bI,O4e as bJ,l4e as bK,O3e as bL,YCe as bM,QCe as bN,Rs as bO,Vle as bP,HCe as bQ,qCe as bR,UCe as bS,Jbe as bT,Am as bU,i4e as bV,N5e as bW,mxe as bX,ble as bY,d5e as bZ,I3e as b_,_ge as ba,$3 as bb,A3e as bc,P3e as bd,cwe as be,mwe as bf,ywe as bg,Bwe as bh,jwe as bi,wwe as bj,qwe as bk,bwe as bl,Iwe as bm,Twe as bn,Jle as bo,Swe as bp,Vwe as bq,vwe as br,Qwe as bs,xwe as bt,Mwe as bu,Cwe as bv,Nwe as bw,Awe as bx,Lwe as by,Zle as bz,AU as c,uxe as c$,eN as c0,O5e as c1,GCe as c2,t3e as c3,T7 as c4,LR as c5,_we as c6,xxe as c7,zn as c8,_5e as c9,Ph as cA,lxe as cB,Zwe as cC,ixe as cD,Fwe as cE,m5e as cF,hl as cG,v5e as cH,r5e as cI,n5e as cJ,t5e as cK,L5e as cL,e4e as cM,l5e as cN,s5e as cO,fe as cP,xf as cQ,W5e as cR,wE as cS,a5e as cT,u5e as cU,o5e as cV,Xse as cW,$we as cX,pQ as cY,j5e as cZ,PR as c_,R5e as ca,k5e as cb,Qae as cc,S5e as cd,C5e as ce,T5e as cf,vQ as cg,vae as ch,bae as ci,pxe as cj,wxe as ck,x5e as cl,_Q as cm,F3e as cn,p5e as co,ER as cp,g3e as cq,f3e as cr,h3e as cs,p3e as ct,B5e as cu,Qa as cv,pwe as cw,xo as cx,ace as cy,kwe as cz,mX as d,pe as d$,bQ as d0,Ui as d1,Dwe as d2,Kwe as d3,gwe as d4,aY as d5,Ywe as d6,i5e as d7,cxe as d8,e5e as d9,d3e as dA,C7 as dB,i3e as dC,s3e as dD,n3e as dE,Spe as dF,r3e as dG,oxe as dH,sxe as dI,nxe as dJ,rxe as dK,txe as dL,X5e as dM,G5e as dN,P5e as dO,U5e as dP,J5e as dQ,K5e as dR,E5e as dS,q5e as dT,H5e as dU,V5e as dV,z5e as dW,GI as dX,Lx as dY,Y5e as dZ,Fm as d_,hce as da,fxe as db,he as dc,Kn as dd,D5e as de,N3e as df,D3e as dg,N7 as dh,F5e as di,M3e as dj,hR as dk,axe as dl,sY as dm,Pwe as dn,$5e as dp,bT as dq,a3e as dr,Hx as ds,tJ as dt,Xl as du,ST as dv,l3e as dw,u3e as dx,c3e as dy,nJ as dz,ZO as e,bpe as e$,Q5e as e0,u2 as e1,Ewe as e2,Z5e as e3,J9 as e4,ak as e5,J3e as e6,q3e as e7,W3e as e8,K3e as e9,cCe as eA,nd as eB,sCe as eC,Vxe as eD,tv as eE,uCe as eF,$xe as eG,aCe as eH,Fxe as eI,Gxe as eJ,Pxe as eK,Exe as eL,Txe as eM,DCe as eN,MR as eO,Cf as eP,Ixe as eQ,Mxe as eR,Nxe as eS,ICe as eT,qxe as eU,Hxe as eV,FQ as eW,RCe as eX,Ele as eY,zxe as eZ,mpe as e_,RM as ea,Q3e as eb,Z3e as ec,Df as ed,_0 as ee,z3e as ef,Dpe as eg,j3e as eh,V3e as ei,G3e as ej,U3e as ek,H3e as el,Y3e as em,$ie as en,eM as eo,oN as ep,CF as eq,Pe as er,gCe as es,NCe as et,MCe as eu,Kxe as ev,CCe as ew,LCe as ex,Ple as ey,jxe as ez,sO as f,aye as f$,Zxe as f0,Jxe as f1,mCe as f2,pCe as f3,dCe as f4,Axe as f5,kxe as f6,I5e as f7,M5e as f8,oCe as f9,yQ as fA,Jwe as fB,Rxe as fC,tCe as fD,jCe as fE,zwe as fF,Uwe as fG,Gwe as fH,Hwe as fI,nCe as fJ,r4e as fK,yxe as fL,AR as fM,Sxe as fN,bxe as fO,_xe as fP,iY as fQ,yle as fR,a4e as fS,iD as fT,S4e as fU,v4e as fV,g4e as fW,b4e as fX,Wi as fY,m4e as fZ,s4e as f_,Qxe as fa,yCe as fb,xCe as fc,vCe as fd,Wxe as fe,Bxe as ff,OCe as fg,kCe as fh,_Ce as fi,bCe as fj,SCe as fk,VCe as fl,PCe as fm,zCe as fn,iCe as fo,rCe as fp,Lxe as fq,Dxe as fr,BCe as fs,Xxe as ft,Tle as fu,wle as fv,xle as fw,Cle as fx,Oxe as fy,dxe as fz,uX as g,Yme as g0,C4e as g1,E4e as g2,P4e as g3,gO as h,vr as i,mc as j,v0 as k,mn as l,y0 as m,hh as n,Ci as o,ta as p,g0 as q,oo as r,gh as s,hb as t,_x as u,iO as v,kx as w,HO as x,aO as y,k as z}; diff --git a/invokeai/frontend/web/dist/index.html b/invokeai/frontend/web/dist/index.html index 315bad4316..2695157ddf 100644 --- a/invokeai/frontend/web/dist/index.html +++ b/invokeai/frontend/web/dist/index.html @@ -12,7 +12,7 @@ margin: 0; } - + diff --git a/invokeai/frontend/web/dist/locales/en.json b/invokeai/frontend/web/dist/locales/en.json index 0640ab9ef0..b9f75ac30f 100644 --- a/invokeai/frontend/web/dist/locales/en.json +++ b/invokeai/frontend/web/dist/locales/en.json @@ -23,6 +23,7 @@ "menu": "Menu" }, "common": { + "communityLabel": "Community", "hotkeysLabel": "Hotkeys", "darkMode": "Dark Mode", "lightMode": "Light Mode", diff --git a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/appConfigReceived.ts b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/appConfigReceived.ts index ef81377f99..2d0ece3595 100644 --- a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/appConfigReceived.ts +++ b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/appConfigReceived.ts @@ -10,8 +10,11 @@ export const addAppConfigReceivedListener = () => { startAppListening({ matcher: appInfoApi.endpoints.getAppConfig.matchFulfilled, effect: async (action, { getState, dispatch }) => { - const { infill_methods, nsfw_methods, watermarking_methods } = - action.payload; + const { + infill_methods = [], + nsfw_methods = [], + watermarking_methods = [], + } = action.payload; const infillMethod = getState().generation.infillMethod; if (!infill_methods.includes(infillMethod)) { diff --git a/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildCanvasImageToImageGraph.ts b/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildCanvasImageToImageGraph.ts index 81e99e0dd0..42f768c107 100644 --- a/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildCanvasImageToImageGraph.ts +++ b/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildCanvasImageToImageGraph.ts @@ -312,6 +312,17 @@ export const buildCanvasImageToImageGraph = ( init_image: initialImage.image_name, }; + graph.edges.push({ + source: { + node_id: METADATA_ACCUMULATOR, + field: 'metadata', + }, + destination: { + node_id: LATENTS_TO_IMAGE, + field: 'metadata', + }, + }); + // add LoRA support addLoRAsToGraph(state, graph, LATENTS_TO_LATENTS); diff --git a/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildCanvasInpaintGraph.ts b/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildCanvasInpaintGraph.ts index 4154c1b5eb..3cec76757f 100644 --- a/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildCanvasInpaintGraph.ts +++ b/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildCanvasInpaintGraph.ts @@ -8,7 +8,9 @@ import { RangeOfSizeInvocation, } from 'services/api/types'; import { addLoRAsToGraph } from './addLoRAsToGraph'; +import { addNSFWCheckerToGraph } from './addNSFWCheckerToGraph'; import { addVAEToGraph } from './addVAEToGraph'; +import { addWatermarkerToGraph } from './addWatermarkerToGraph'; import { CLIP_SKIP, INPAINT, @@ -20,8 +22,6 @@ import { RANDOM_INT, RANGE_OF_SIZE, } from './constants'; -import { addNSFWCheckerToGraph } from './addNSFWCheckerToGraph'; -import { addWatermarkerToGraph } from './addWatermarkerToGraph'; /** * Builds the Canvas tab's Inpaint graph. diff --git a/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildCanvasTextToImageGraph.ts b/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildCanvasTextToImageGraph.ts index 597a643367..13b27392ba 100644 --- a/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildCanvasTextToImageGraph.ts +++ b/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildCanvasTextToImageGraph.ts @@ -217,6 +217,17 @@ export const buildCanvasTextToImageGraph = ( clip_skip: clipSkip, }; + graph.edges.push({ + source: { + node_id: METADATA_ACCUMULATOR, + field: 'metadata', + }, + destination: { + node_id: LATENTS_TO_IMAGE, + field: 'metadata', + }, + }); + // add LoRA support addLoRAsToGraph(state, graph, TEXT_TO_LATENTS); diff --git a/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildLinearImageToImageGraph.ts b/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildLinearImageToImageGraph.ts index d78e2e1356..f264edc6be 100644 --- a/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildLinearImageToImageGraph.ts +++ b/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildLinearImageToImageGraph.ts @@ -322,6 +322,17 @@ export const buildLinearImageToImageGraph = ( init_image: initialImage.imageName, }; + graph.edges.push({ + source: { + node_id: METADATA_ACCUMULATOR, + field: 'metadata', + }, + destination: { + node_id: LATENTS_TO_IMAGE, + field: 'metadata', + }, + }); + // add LoRA support addLoRAsToGraph(state, graph, LATENTS_TO_LATENTS); diff --git a/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildLinearTextToImageGraph.ts b/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildLinearTextToImageGraph.ts index 94f35feba0..3766ac1ee3 100644 --- a/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildLinearTextToImageGraph.ts +++ b/invokeai/frontend/web/src/features/nodes/util/graphBuilders/buildLinearTextToImageGraph.ts @@ -206,6 +206,17 @@ export const buildLinearTextToImageGraph = ( clip_skip: clipSkip, }; + graph.edges.push({ + source: { + node_id: METADATA_ACCUMULATOR, + field: 'metadata', + }, + destination: { + node_id: LATENTS_TO_IMAGE, + field: 'metadata', + }, + }); + // add LoRA support addLoRAsToGraph(state, graph, TEXT_TO_LATENTS); diff --git a/invokeai/frontend/web/src/features/ui/components/InvokeTabs.tsx b/invokeai/frontend/web/src/features/ui/components/InvokeTabs.tsx index 26d06adfb3..87ce801ead 100644 --- a/invokeai/frontend/web/src/features/ui/components/InvokeTabs.tsx +++ b/invokeai/frontend/web/src/features/ui/components/InvokeTabs.tsx @@ -227,7 +227,8 @@ const InvokeTabs = () => { id="gallery" order={3} defaultSize={ - galleryMinSizePct > DEFAULT_GALLERY_PCT + galleryMinSizePct > DEFAULT_GALLERY_PCT && + galleryMinSizePct < 100 // prevent this error https://github.com/bvaughn/react-resizable-panels/blob/main/packages/react-resizable-panels/src/Panel.ts#L96 ? galleryMinSizePct : DEFAULT_GALLERY_PCT } diff --git a/invokeai/frontend/web/src/services/api/schema.d.ts b/invokeai/frontend/web/src/services/api/schema.d.ts index c8e87ef8c5..8d3b55aa88 100644 --- a/invokeai/frontend/web/src/services/api/schema.d.ts +++ b/invokeai/frontend/web/src/services/api/schema.d.ts @@ -901,8 +901,8 @@ export type components = { */ resize_mode?: "just_resize" | "crop_resize" | "fill_resize" | "just_resize_simple"; }; - /** ControlNetModelConfig */ - ControlNetModelConfig: { + /** ControlNetModelCheckpointConfig */ + ControlNetModelCheckpointConfig: { /** Model Name */ model_name: string; base_model: components["schemas"]["BaseModelType"]; @@ -915,7 +915,34 @@ export type components = { path: string; /** Description */ description?: string; - model_format: components["schemas"]["ControlNetModelFormat"]; + /** + * Model Format + * @enum {string} + */ + model_format: "checkpoint"; + error?: components["schemas"]["ModelError"]; + /** Config */ + config: string; + }; + /** ControlNetModelDiffusersConfig */ + ControlNetModelDiffusersConfig: { + /** Model Name */ + model_name: string; + base_model: components["schemas"]["BaseModelType"]; + /** + * Model Type + * @enum {string} + */ + model_type: "controlnet"; + /** Path */ + path: string; + /** Description */ + description?: string; + /** + * Model Format + * @enum {string} + */ + model_format: "diffusers"; error?: components["schemas"]["ModelError"]; }; /** @@ -931,12 +958,6 @@ export type components = { /** @description Base model */ base_model: components["schemas"]["BaseModelType"]; }; - /** - * ControlNetModelFormat - * @description An enumeration. - * @enum {string} - */ - ControlNetModelFormat: "checkpoint" | "diffusers"; /** * ControlOutput * @description node output for ControlNet info @@ -1360,7 +1381,7 @@ export type components = { * @description The nodes in this graph */ nodes?: { - [key: string]: (components["schemas"]["ControlNetInvocation"] | components["schemas"]["ImageProcessorInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["LoraLoaderInvocation"] | components["schemas"]["VaeLoaderInvocation"] | components["schemas"]["MetadataAccumulatorInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRawPromptInvocation"] | components["schemas"]["SDXLRefinerRawPromptInvocation"] | components["schemas"]["ClipSkipInvocation"] | components["schemas"]["LoadImageInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["TextToLatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SDXLTextToLatentsInvocation"] | components["schemas"]["SDXLLatentsToLatentsInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["AddInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["ParamIntInvocation"] | components["schemas"]["ParamFloatInvocation"] | components["schemas"]["ParamStringInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["StepParamEasingInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["InpaintInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["GraphInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["CannyImageProcessorInvocation"] | components["schemas"]["HedImageProcessorInvocation"] | components["schemas"]["LineartImageProcessorInvocation"] | components["schemas"]["LineartAnimeImageProcessorInvocation"] | components["schemas"]["OpenposeImageProcessorInvocation"] | components["schemas"]["MidasDepthImageProcessorInvocation"] | components["schemas"]["NormalbaeImageProcessorInvocation"] | components["schemas"]["MlsdImageProcessorInvocation"] | components["schemas"]["PidiImageProcessorInvocation"] | components["schemas"]["ContentShuffleImageProcessorInvocation"] | components["schemas"]["ZoeDepthImageProcessorInvocation"] | components["schemas"]["MediapipeFaceProcessorInvocation"] | components["schemas"]["LeresImageProcessorInvocation"] | components["schemas"]["TileResamplerProcessorInvocation"] | components["schemas"]["SegmentAnythingProcessorInvocation"] | components["schemas"]["LatentsToLatentsInvocation"]) | undefined; + [key: string]: (components["schemas"]["ControlNetInvocation"] | components["schemas"]["ImageProcessorInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["LoraLoaderInvocation"] | components["schemas"]["VaeLoaderInvocation"] | components["schemas"]["MetadataAccumulatorInvocation"] | components["schemas"]["LoadImageInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRawPromptInvocation"] | components["schemas"]["SDXLRefinerRawPromptInvocation"] | components["schemas"]["ClipSkipInvocation"] | components["schemas"]["TextToLatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["InpaintInvocation"] | components["schemas"]["AddInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["ParamIntInvocation"] | components["schemas"]["ParamFloatInvocation"] | components["schemas"]["ParamStringInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SDXLTextToLatentsInvocation"] | components["schemas"]["SDXLLatentsToLatentsInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["StepParamEasingInvocation"] | components["schemas"]["GraphInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["CannyImageProcessorInvocation"] | components["schemas"]["HedImageProcessorInvocation"] | components["schemas"]["LineartImageProcessorInvocation"] | components["schemas"]["LineartAnimeImageProcessorInvocation"] | components["schemas"]["OpenposeImageProcessorInvocation"] | components["schemas"]["MidasDepthImageProcessorInvocation"] | components["schemas"]["NormalbaeImageProcessorInvocation"] | components["schemas"]["MlsdImageProcessorInvocation"] | components["schemas"]["PidiImageProcessorInvocation"] | components["schemas"]["ContentShuffleImageProcessorInvocation"] | components["schemas"]["ZoeDepthImageProcessorInvocation"] | components["schemas"]["MediapipeFaceProcessorInvocation"] | components["schemas"]["LeresImageProcessorInvocation"] | components["schemas"]["TileResamplerProcessorInvocation"] | components["schemas"]["SegmentAnythingProcessorInvocation"] | components["schemas"]["LatentsToLatentsInvocation"]) | undefined; }; /** * Edges @@ -1403,7 +1424,7 @@ export type components = { * @description The results of node executions */ results: { - [key: string]: (components["schemas"]["ImageOutput"] | components["schemas"]["MaskOutput"] | components["schemas"]["ControlOutput"] | components["schemas"]["ModelLoaderOutput"] | components["schemas"]["LoraLoaderOutput"] | components["schemas"]["VaeLoaderOutput"] | components["schemas"]["MetadataAccumulatorOutput"] | components["schemas"]["CompelOutput"] | components["schemas"]["ClipSkipInvocationOutput"] | components["schemas"]["LatentsOutput"] | components["schemas"]["SDXLModelLoaderOutput"] | components["schemas"]["SDXLRefinerModelLoaderOutput"] | components["schemas"]["PromptOutput"] | components["schemas"]["PromptCollectionOutput"] | components["schemas"]["IntOutput"] | components["schemas"]["FloatOutput"] | components["schemas"]["StringOutput"] | components["schemas"]["IntCollectionOutput"] | components["schemas"]["FloatCollectionOutput"] | components["schemas"]["ImageCollectionOutput"] | components["schemas"]["NoiseOutput"] | components["schemas"]["GraphInvocationOutput"] | components["schemas"]["IterateInvocationOutput"] | components["schemas"]["CollectInvocationOutput"]) | undefined; + [key: string]: (components["schemas"]["ImageOutput"] | components["schemas"]["MaskOutput"] | components["schemas"]["ControlOutput"] | components["schemas"]["ModelLoaderOutput"] | components["schemas"]["LoraLoaderOutput"] | components["schemas"]["VaeLoaderOutput"] | components["schemas"]["MetadataAccumulatorOutput"] | components["schemas"]["CompelOutput"] | components["schemas"]["ClipSkipInvocationOutput"] | components["schemas"]["LatentsOutput"] | components["schemas"]["IntOutput"] | components["schemas"]["FloatOutput"] | components["schemas"]["StringOutput"] | components["schemas"]["IntCollectionOutput"] | components["schemas"]["FloatCollectionOutput"] | components["schemas"]["ImageCollectionOutput"] | components["schemas"]["PromptOutput"] | components["schemas"]["PromptCollectionOutput"] | components["schemas"]["NoiseOutput"] | components["schemas"]["SDXLModelLoaderOutput"] | components["schemas"]["SDXLRefinerModelLoaderOutput"] | components["schemas"]["GraphInvocationOutput"] | components["schemas"]["IterateInvocationOutput"] | components["schemas"]["CollectInvocationOutput"]) | undefined; }; /** * Errors @@ -3607,7 +3628,7 @@ export type components = { /** ModelsList */ ModelsList: { /** Models */ - models: (components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"])[]; + models: (components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelCheckpointConfig"] | components["schemas"]["ControlNetModelDiffusersConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"])[]; }; /** * MultiplyInvocation @@ -5535,24 +5556,30 @@ export type components = { */ image?: components["schemas"]["ImageField"]; }; - /** - * StableDiffusion1ModelFormat - * @description An enumeration. - * @enum {string} - */ - StableDiffusion1ModelFormat: "checkpoint" | "diffusers"; /** * StableDiffusion2ModelFormat * @description An enumeration. * @enum {string} */ StableDiffusion2ModelFormat: "checkpoint" | "diffusers"; + /** + * StableDiffusion1ModelFormat + * @description An enumeration. + * @enum {string} + */ + StableDiffusion1ModelFormat: "checkpoint" | "diffusers"; /** * StableDiffusionXLModelFormat * @description An enumeration. * @enum {string} */ StableDiffusionXLModelFormat: "checkpoint" | "diffusers"; + /** + * ControlNetModelFormat + * @description An enumeration. + * @enum {string} + */ + ControlNetModelFormat: "checkpoint" | "diffusers"; }; responses: never; parameters: never; @@ -5663,7 +5690,7 @@ export type operations = { }; requestBody: { content: { - "application/json": components["schemas"]["ControlNetInvocation"] | components["schemas"]["ImageProcessorInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["LoraLoaderInvocation"] | components["schemas"]["VaeLoaderInvocation"] | components["schemas"]["MetadataAccumulatorInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRawPromptInvocation"] | components["schemas"]["SDXLRefinerRawPromptInvocation"] | components["schemas"]["ClipSkipInvocation"] | components["schemas"]["LoadImageInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["TextToLatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SDXLTextToLatentsInvocation"] | components["schemas"]["SDXLLatentsToLatentsInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["AddInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["ParamIntInvocation"] | components["schemas"]["ParamFloatInvocation"] | components["schemas"]["ParamStringInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["StepParamEasingInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["InpaintInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["GraphInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["CannyImageProcessorInvocation"] | components["schemas"]["HedImageProcessorInvocation"] | components["schemas"]["LineartImageProcessorInvocation"] | components["schemas"]["LineartAnimeImageProcessorInvocation"] | components["schemas"]["OpenposeImageProcessorInvocation"] | components["schemas"]["MidasDepthImageProcessorInvocation"] | components["schemas"]["NormalbaeImageProcessorInvocation"] | components["schemas"]["MlsdImageProcessorInvocation"] | components["schemas"]["PidiImageProcessorInvocation"] | components["schemas"]["ContentShuffleImageProcessorInvocation"] | components["schemas"]["ZoeDepthImageProcessorInvocation"] | components["schemas"]["MediapipeFaceProcessorInvocation"] | components["schemas"]["LeresImageProcessorInvocation"] | components["schemas"]["TileResamplerProcessorInvocation"] | components["schemas"]["SegmentAnythingProcessorInvocation"] | components["schemas"]["LatentsToLatentsInvocation"]; + "application/json": components["schemas"]["ControlNetInvocation"] | components["schemas"]["ImageProcessorInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["LoraLoaderInvocation"] | components["schemas"]["VaeLoaderInvocation"] | components["schemas"]["MetadataAccumulatorInvocation"] | components["schemas"]["LoadImageInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRawPromptInvocation"] | components["schemas"]["SDXLRefinerRawPromptInvocation"] | components["schemas"]["ClipSkipInvocation"] | components["schemas"]["TextToLatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["InpaintInvocation"] | components["schemas"]["AddInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["ParamIntInvocation"] | components["schemas"]["ParamFloatInvocation"] | components["schemas"]["ParamStringInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SDXLTextToLatentsInvocation"] | components["schemas"]["SDXLLatentsToLatentsInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["StepParamEasingInvocation"] | components["schemas"]["GraphInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["CannyImageProcessorInvocation"] | components["schemas"]["HedImageProcessorInvocation"] | components["schemas"]["LineartImageProcessorInvocation"] | components["schemas"]["LineartAnimeImageProcessorInvocation"] | components["schemas"]["OpenposeImageProcessorInvocation"] | components["schemas"]["MidasDepthImageProcessorInvocation"] | components["schemas"]["NormalbaeImageProcessorInvocation"] | components["schemas"]["MlsdImageProcessorInvocation"] | components["schemas"]["PidiImageProcessorInvocation"] | components["schemas"]["ContentShuffleImageProcessorInvocation"] | components["schemas"]["ZoeDepthImageProcessorInvocation"] | components["schemas"]["MediapipeFaceProcessorInvocation"] | components["schemas"]["LeresImageProcessorInvocation"] | components["schemas"]["TileResamplerProcessorInvocation"] | components["schemas"]["SegmentAnythingProcessorInvocation"] | components["schemas"]["LatentsToLatentsInvocation"]; }; }; responses: { @@ -5700,7 +5727,7 @@ export type operations = { }; requestBody: { content: { - "application/json": components["schemas"]["ControlNetInvocation"] | components["schemas"]["ImageProcessorInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["LoraLoaderInvocation"] | components["schemas"]["VaeLoaderInvocation"] | components["schemas"]["MetadataAccumulatorInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRawPromptInvocation"] | components["schemas"]["SDXLRefinerRawPromptInvocation"] | components["schemas"]["ClipSkipInvocation"] | components["schemas"]["LoadImageInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["TextToLatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SDXLTextToLatentsInvocation"] | components["schemas"]["SDXLLatentsToLatentsInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["AddInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["ParamIntInvocation"] | components["schemas"]["ParamFloatInvocation"] | components["schemas"]["ParamStringInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["StepParamEasingInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["InpaintInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["GraphInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["CannyImageProcessorInvocation"] | components["schemas"]["HedImageProcessorInvocation"] | components["schemas"]["LineartImageProcessorInvocation"] | components["schemas"]["LineartAnimeImageProcessorInvocation"] | components["schemas"]["OpenposeImageProcessorInvocation"] | components["schemas"]["MidasDepthImageProcessorInvocation"] | components["schemas"]["NormalbaeImageProcessorInvocation"] | components["schemas"]["MlsdImageProcessorInvocation"] | components["schemas"]["PidiImageProcessorInvocation"] | components["schemas"]["ContentShuffleImageProcessorInvocation"] | components["schemas"]["ZoeDepthImageProcessorInvocation"] | components["schemas"]["MediapipeFaceProcessorInvocation"] | components["schemas"]["LeresImageProcessorInvocation"] | components["schemas"]["TileResamplerProcessorInvocation"] | components["schemas"]["SegmentAnythingProcessorInvocation"] | components["schemas"]["LatentsToLatentsInvocation"]; + "application/json": components["schemas"]["ControlNetInvocation"] | components["schemas"]["ImageProcessorInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["LoraLoaderInvocation"] | components["schemas"]["VaeLoaderInvocation"] | components["schemas"]["MetadataAccumulatorInvocation"] | components["schemas"]["LoadImageInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRawPromptInvocation"] | components["schemas"]["SDXLRefinerRawPromptInvocation"] | components["schemas"]["ClipSkipInvocation"] | components["schemas"]["TextToLatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["InpaintInvocation"] | components["schemas"]["AddInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["ParamIntInvocation"] | components["schemas"]["ParamFloatInvocation"] | components["schemas"]["ParamStringInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SDXLTextToLatentsInvocation"] | components["schemas"]["SDXLLatentsToLatentsInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["StepParamEasingInvocation"] | components["schemas"]["GraphInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["CannyImageProcessorInvocation"] | components["schemas"]["HedImageProcessorInvocation"] | components["schemas"]["LineartImageProcessorInvocation"] | components["schemas"]["LineartAnimeImageProcessorInvocation"] | components["schemas"]["OpenposeImageProcessorInvocation"] | components["schemas"]["MidasDepthImageProcessorInvocation"] | components["schemas"]["NormalbaeImageProcessorInvocation"] | components["schemas"]["MlsdImageProcessorInvocation"] | components["schemas"]["PidiImageProcessorInvocation"] | components["schemas"]["ContentShuffleImageProcessorInvocation"] | components["schemas"]["ZoeDepthImageProcessorInvocation"] | components["schemas"]["MediapipeFaceProcessorInvocation"] | components["schemas"]["LeresImageProcessorInvocation"] | components["schemas"]["TileResamplerProcessorInvocation"] | components["schemas"]["SegmentAnythingProcessorInvocation"] | components["schemas"]["LatentsToLatentsInvocation"]; }; }; responses: { @@ -5964,14 +5991,14 @@ export type operations = { }; requestBody: { content: { - "application/json": components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"]; + "application/json": components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelCheckpointConfig"] | components["schemas"]["ControlNetModelDiffusersConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"]; }; }; responses: { /** @description The model was updated successfully */ 200: { content: { - "application/json": components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"]; + "application/json": components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelCheckpointConfig"] | components["schemas"]["ControlNetModelDiffusersConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"]; }; }; /** @description Bad request */ @@ -6002,7 +6029,7 @@ export type operations = { /** @description The model imported successfully */ 201: { content: { - "application/json": components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"]; + "application/json": components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelCheckpointConfig"] | components["schemas"]["ControlNetModelDiffusersConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"]; }; }; /** @description The model could not be found */ @@ -6028,14 +6055,14 @@ export type operations = { add_model: { requestBody: { content: { - "application/json": components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"]; + "application/json": components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelCheckpointConfig"] | components["schemas"]["ControlNetModelDiffusersConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"]; }; }; responses: { /** @description The model added successfully */ 201: { content: { - "application/json": components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"]; + "application/json": components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelCheckpointConfig"] | components["schemas"]["ControlNetModelDiffusersConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"]; }; }; /** @description The model could not be found */ @@ -6075,7 +6102,7 @@ export type operations = { /** @description Model converted successfully */ 200: { content: { - "application/json": components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"]; + "application/json": components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelCheckpointConfig"] | components["schemas"]["ControlNetModelDiffusersConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"]; }; }; /** @description Bad request */ @@ -6164,7 +6191,7 @@ export type operations = { /** @description Model converted successfully */ 200: { content: { - "application/json": components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"]; + "application/json": components["schemas"]["StableDiffusion1ModelCheckpointConfig"] | components["schemas"]["StableDiffusion1ModelDiffusersConfig"] | components["schemas"]["VaeModelConfig"] | components["schemas"]["LoRAModelConfig"] | components["schemas"]["ControlNetModelCheckpointConfig"] | components["schemas"]["ControlNetModelDiffusersConfig"] | components["schemas"]["TextualInversionModelConfig"] | components["schemas"]["StableDiffusion2ModelCheckpointConfig"] | components["schemas"]["StableDiffusion2ModelDiffusersConfig"] | components["schemas"]["StableDiffusionXLModelCheckpointConfig"] | components["schemas"]["StableDiffusionXLModelDiffusersConfig"]; }; }; /** @description Incompatible models */ diff --git a/invokeai/version/__init__.py b/invokeai/version/__init__.py index 01ef84ea4d..21dfcad3ca 100644 --- a/invokeai/version/__init__.py +++ b/invokeai/version/__init__.py @@ -6,6 +6,7 @@ from .invokeai_version import __version__ __app_id__ = "invoke-ai/InvokeAI" __app_name__ = "InvokeAI" + def _ignore_xformers_triton_message_on_windows(): import logging diff --git a/invokeai/version/invokeai_version.py b/invokeai/version/invokeai_version.py index 528787cfc8..ebc585fb61 100644 --- a/invokeai/version/invokeai_version.py +++ b/invokeai/version/invokeai_version.py @@ -1 +1 @@ -__version__ = "3.0.0" +__version__ = "3.0.1rc1" diff --git a/notebooks/notebook_helpers.py b/notebooks/notebook_helpers.py index 663b212ac5..b87f18ba18 100644 --- a/notebooks/notebook_helpers.py +++ b/notebooks/notebook_helpers.py @@ -2,6 +2,7 @@ from torchvision.datasets.utils import download_url from ldm.util import instantiate_from_config import torch import os + # todo ? from google.colab import files from IPython.display import Image as ipyimg @@ -16,21 +17,21 @@ import time from omegaconf import OmegaConf from ldm.invoke.devices import choose_torch_device -def download_models(mode): +def download_models(mode): if mode == "superresolution": # this is the small bsr light model - url_conf = 'https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1' - url_ckpt = 'https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1' + url_conf = "https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1" + url_ckpt = "https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1" - path_conf = 'logs/diffusion/superresolution_bsr/configs/project.yaml' - path_ckpt = 'logs/diffusion/superresolution_bsr/checkpoints/last.ckpt' + path_conf = "logs/diffusion/superresolution_bsr/configs/project.yaml" + path_ckpt = "logs/diffusion/superresolution_bsr/checkpoints/last.ckpt" download_url(url_conf, path_conf) download_url(url_ckpt, path_ckpt) - path_conf = path_conf + '/?dl=1' # fix it - path_ckpt = path_ckpt + '/?dl=1' # fix it + path_conf = path_conf + "/?dl=1" # fix it + path_ckpt = path_ckpt + "/?dl=1" # fix it return path_conf, path_ckpt else: @@ -62,20 +63,20 @@ def get_custom_cond(mode): if mode == "superresolution": uploaded_img = files.upload() filename = next(iter(uploaded_img)) - name, filetype = filename.split(".") # todo assumes just one dot in name ! + name, filetype = filename.split(".") # todo assumes just one dot in name ! os.rename(f"{filename}", f"{dest}/{mode}/custom_{name}.{filetype}") elif mode == "text_conditional": - w = widgets.Text(value='A cake with cream!', disabled=True) + w = widgets.Text(value="A cake with cream!", disabled=True) display(w) - with open(f"{dest}/{mode}/custom_{w.value[:20]}.txt", 'w') as f: + with open(f"{dest}/{mode}/custom_{w.value[:20]}.txt", "w") as f: f.write(w.value) elif mode == "class_conditional": w = widgets.IntSlider(min=0, max=1000) display(w) - with open(f"{dest}/{mode}/custom.txt", 'w') as f: + with open(f"{dest}/{mode}/custom.txt", "w") as f: f.write(w.value) else: @@ -94,11 +95,7 @@ def select_cond_path(mode): path = os.path.join(path, mode) onlyfiles = [f for f in sorted(os.listdir(path))] - selected = widgets.RadioButtons( - options=onlyfiles, - description='Select conditioning:', - disabled=False - ) + selected = widgets.RadioButtons(options=onlyfiles, description="Select conditioning:", disabled=False) display(selected) selected_path = os.path.join(path, selected.value) return selected_path @@ -113,9 +110,9 @@ def get_cond(mode, selected_path): c = Image.open(selected_path) c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0) c_up = torchvision.transforms.functional.resize(c, size=[up_f * c.shape[2], up_f * c.shape[3]], antialias=True) - c_up = rearrange(c_up, '1 c h w -> 1 h w c') - c = rearrange(c, '1 c h w -> 1 h w c') - c = 2. * c - 1. + c_up = rearrange(c_up, "1 c h w -> 1 h w c") + c = rearrange(c, "1 c h w -> 1 h w c") + c = 2.0 * c - 1.0 device = choose_torch_device() c = c.to(device) @@ -130,7 +127,6 @@ def visualize_cond_img(path): def run(model, selected_path, task, custom_steps, resize_enabled=False, classifier_ckpt=None, global_step=None): - example = get_cond(task, selected_path) save_intermediate_vid = False @@ -138,10 +134,10 @@ def run(model, selected_path, task, custom_steps, resize_enabled=False, classifi masked = False guider = None ckwargs = None - mode = 'ddim' + mode = "ddim" ddim_use_x0_pred = False - temperature = 1. - eta = 1. + temperature = 1.0 + eta = 1.0 make_progrow = True custom_shape = None @@ -152,14 +148,17 @@ def run(model, selected_path, task, custom_steps, resize_enabled=False, classifi ks = 128 stride = 64 vqf = 4 # - model.split_input_params = {"ks": (ks, ks), "stride": (stride, stride), - "vqf": vqf, - "patch_distributed_vq": True, - "tie_braker": False, - "clip_max_weight": 0.5, - "clip_min_weight": 0.01, - "clip_max_tie_weight": 0.5, - "clip_min_tie_weight": 0.01} + model.split_input_params = { + "ks": (ks, ks), + "stride": (stride, stride), + "vqf": vqf, + "patch_distributed_vq": True, + "tie_braker": False, + "clip_max_weight": 0.5, + "clip_min_weight": 0.01, + "clip_max_tie_weight": 0.5, + "clip_min_tie_weight": 0.01, + } else: if hasattr(model, "split_input_params"): delattr(model, "split_input_params") @@ -170,53 +169,112 @@ def run(model, selected_path, task, custom_steps, resize_enabled=False, classifi for n in range(n_runs): if custom_shape is not None: x_T = torch.randn(1, custom_shape[1], custom_shape[2], custom_shape[3]).to(model.device) - x_T = repeat(x_T, '1 c h w -> b c h w', b=custom_shape[0]) + x_T = repeat(x_T, "1 c h w -> b c h w", b=custom_shape[0]) - logs = make_convolutional_sample(example, model, - mode=mode, custom_steps=custom_steps, - eta=eta, swap_mode=False , masked=masked, - invert_mask=invert_mask, quantize_x0=False, - custom_schedule=None, decode_interval=10, - resize_enabled=resize_enabled, custom_shape=custom_shape, - temperature=temperature, noise_dropout=0., - corrector=guider, corrector_kwargs=ckwargs, x_T=x_T, save_intermediate_vid=save_intermediate_vid, - make_progrow=make_progrow,ddim_use_x0_pred=ddim_use_x0_pred - ) + logs = make_convolutional_sample( + example, + model, + mode=mode, + custom_steps=custom_steps, + eta=eta, + swap_mode=False, + masked=masked, + invert_mask=invert_mask, + quantize_x0=False, + custom_schedule=None, + decode_interval=10, + resize_enabled=resize_enabled, + custom_shape=custom_shape, + temperature=temperature, + noise_dropout=0.0, + corrector=guider, + corrector_kwargs=ckwargs, + x_T=x_T, + save_intermediate_vid=save_intermediate_vid, + make_progrow=make_progrow, + ddim_use_x0_pred=ddim_use_x0_pred, + ) return logs @torch.no_grad() -def convsample_ddim(model, cond, steps, shape, eta=1.0, callback=None, normals_sequence=None, - mask=None, x0=None, quantize_x0=False, img_callback=None, - temperature=1., noise_dropout=0., score_corrector=None, - corrector_kwargs=None, x_T=None, log_every_t=None - ): - +def convsample_ddim( + model, + cond, + steps, + shape, + eta=1.0, + callback=None, + normals_sequence=None, + mask=None, + x0=None, + quantize_x0=False, + img_callback=None, + temperature=1.0, + noise_dropout=0.0, + score_corrector=None, + corrector_kwargs=None, + x_T=None, + log_every_t=None, +): ddim = DDIMSampler(model) bs = shape[0] # dont know where this comes from but wayne shape = shape[1:] # cut batch dim print(f"Sampling with eta = {eta}; steps: {steps}") - samples, intermediates = ddim.sample(steps, batch_size=bs, shape=shape, conditioning=cond, callback=callback, - normals_sequence=normals_sequence, quantize_x0=quantize_x0, eta=eta, - mask=mask, x0=x0, temperature=temperature, verbose=False, - score_corrector=score_corrector, - corrector_kwargs=corrector_kwargs, x_T=x_T) + samples, intermediates = ddim.sample( + steps, + batch_size=bs, + shape=shape, + conditioning=cond, + callback=callback, + normals_sequence=normals_sequence, + quantize_x0=quantize_x0, + eta=eta, + mask=mask, + x0=x0, + temperature=temperature, + verbose=False, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + x_T=x_T, + ) return samples, intermediates @torch.no_grad() -def make_convolutional_sample(batch, model, mode="vanilla", custom_steps=None, eta=1.0, swap_mode=False, masked=False, - invert_mask=True, quantize_x0=False, custom_schedule=None, decode_interval=1000, - resize_enabled=False, custom_shape=None, temperature=1., noise_dropout=0., corrector=None, - corrector_kwargs=None, x_T=None, save_intermediate_vid=False, make_progrow=True,ddim_use_x0_pred=False): +def make_convolutional_sample( + batch, + model, + mode="vanilla", + custom_steps=None, + eta=1.0, + swap_mode=False, + masked=False, + invert_mask=True, + quantize_x0=False, + custom_schedule=None, + decode_interval=1000, + resize_enabled=False, + custom_shape=None, + temperature=1.0, + noise_dropout=0.0, + corrector=None, + corrector_kwargs=None, + x_T=None, + save_intermediate_vid=False, + make_progrow=True, + ddim_use_x0_pred=False, +): log = dict() - z, c, x, xrec, xc = model.get_input(batch, model.first_stage_key, - return_first_stage_outputs=True, - force_c_encode=not (hasattr(model, 'split_input_params') - and model.cond_stage_key == 'coordinates_bbox'), - return_original_cond=True) + z, c, x, xrec, xc = model.get_input( + batch, + model.first_stage_key, + return_first_stage_outputs=True, + force_c_encode=not (hasattr(model, "split_input_params") and model.cond_stage_key == "coordinates_bbox"), + return_original_cond=True, + ) log_every_t = 1 if save_intermediate_vid else None @@ -231,30 +289,41 @@ def make_convolutional_sample(batch, model, mode="vanilla", custom_steps=None, e if ismap(xc): log["original_conditioning"] = model.to_rgb(xc) - if hasattr(model, 'cond_stage_key'): + if hasattr(model, "cond_stage_key"): log[model.cond_stage_key] = model.to_rgb(xc) else: log["original_conditioning"] = xc if xc is not None else torch.zeros_like(x) if model.cond_stage_model: log[model.cond_stage_key] = xc if xc is not None else torch.zeros_like(x) - if model.cond_stage_key =='class_label': + if model.cond_stage_key == "class_label": log[model.cond_stage_key] = xc[model.cond_stage_key] with model.ema_scope("Plotting"): t0 = time.time() img_cb = None - sample, intermediates = convsample_ddim(model, c, steps=custom_steps, shape=z.shape, - eta=eta, - quantize_x0=quantize_x0, img_callback=img_cb, mask=None, x0=z0, - temperature=temperature, noise_dropout=noise_dropout, - score_corrector=corrector, corrector_kwargs=corrector_kwargs, - x_T=x_T, log_every_t=log_every_t) + sample, intermediates = convsample_ddim( + model, + c, + steps=custom_steps, + shape=z.shape, + eta=eta, + quantize_x0=quantize_x0, + img_callback=img_cb, + mask=None, + x0=z0, + temperature=temperature, + noise_dropout=noise_dropout, + score_corrector=corrector, + corrector_kwargs=corrector_kwargs, + x_T=x_T, + log_every_t=log_every_t, + ) t1 = time.time() if ddim_use_x0_pred: - sample = intermediates['pred_x0'][-1] + sample = intermediates["pred_x0"][-1] x_sample = model.decode_first_stage(sample) diff --git a/pyproject.toml b/pyproject.toml index bac2b3dc24..a97830c670 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta" [project] name = "InvokeAI" description = "An implementation of Stable Diffusion which provides various new features and options to aid the image generation process" -requires-python = ">=3.9, <3.11" +requires-python = ">=3.9, <3.12" readme = { content-type = "text/markdown", file = "README.md" } keywords = ["stable-diffusion", "AI"] dynamic = ["version"] @@ -32,16 +32,16 @@ classifiers = [ 'Topic :: Scientific/Engineering :: Image Processing', ] dependencies = [ - "accelerate~=0.16", + "accelerate~=0.21.0", "albumentations", "click", - "clip_anytorch", # replacing "clip @ https://github.com/openai/CLIP/archive/eaa22acb90a5876642d0507623e859909230a52d.zip", - "compel==2.0.0", + "clip_anytorch", # replacing "clip @ https://github.com/openai/CLIP/archive/eaa22acb90a5876642d0507623e859909230a52d.zip", + "compel~=2.0.0", "controlnet-aux>=0.0.6", - "timm==0.6.13", # needed to override timm latest in controlnet_aux, see https://github.com/isl-org/ZoeDepth/issues/26 + "timm==0.6.13", # needed to override timm latest in controlnet_aux, see https://github.com/isl-org/ZoeDepth/issues/26 "datasets", "diffusers[torch]~=0.19.0", - "dnspython==2.2.1", + "dnspython~=2.4.0", "dynamicprompts", "easing-functions", "einops", @@ -54,37 +54,37 @@ dependencies = [ "flask_cors==3.0.10", "flask_socketio==5.3.0", "flaskwebgui==1.0.3", - "gfpgan==1.3.8", "huggingface-hub>=0.11.1", - "invisible-watermark>=0.2.0", # needed to install SDXL base and refiner using their repo_ids + "invisible-watermark~=0.2.0", # needed to install SDXL base and refiner using their repo_ids "matplotlib", # needed for plotting of Penner easing functions "mediapipe", # needed for "mediapipeface" controlnet model "npyscreen", - "numpy<1.24", + "numpy==1.24.4", "omegaconf", "opencv-python", "picklescan", "pillow", "prompt-toolkit", - "pympler==1.0.1", + "pydantic==1.10.10", + "pympler~=1.0.1", "pypatchmatch", 'pyperclip', "pyreadline3", - "python-multipart==0.0.6", - "pytorch-lightning==1.7.7", + "python-multipart", + "pytorch-lightning", "realesrgan", - "requests==2.28.2", + "requests~=2.28.2", "rich~=13.3", "safetensors~=0.3.0", - "scikit-image>=0.19", + "scikit-image~=0.21.0", "send2trash", - "test-tube>=0.7.5", - "torch~=2.0.0", - "torchvision>=0.14.1", - "torchmetrics==0.11.4", - "torchsde==0.2.5", + "test-tube~=0.7.5", + "torch~=2.0.1", + "torchvision~=0.15.2", + "torchmetrics~=1.0.1", + "torchsde~=0.2.5", "transformers~=4.31.0", - "uvicorn[standard]==0.21.1", + "uvicorn[standard]~=0.21.1", "windows-curses; sys_platform=='win32'", ] @@ -98,7 +98,7 @@ dependencies = [ "dev" = [ "pudb", ] -"test" = ["pytest>6.0.0", "pytest-cov"] +"test" = ["pytest>6.0.0", "pytest-cov", "black"] "xformers" = [ "xformers~=0.0.19; sys_platform!='darwin'", "triton; sys_platform=='linux'", @@ -176,5 +176,8 @@ directory = "coverage/html" output = "coverage/index.xml" #=== End: PyTest and Coverage -[flake8] +[tool.flake8] max-line-length = 120 + +[tool.black] +line-length = 120 \ No newline at end of file diff --git a/scripts/configure_invokeai.py b/scripts/configure_invokeai.py index 0226fa1c2a..61d32b6df5 100755 --- a/scripts/configure_invokeai.py +++ b/scripts/configure_invokeai.py @@ -4,6 +4,6 @@ import warnings from invokeai.frontend.install import invokeai_configure as configure -if __name__ == '__main__': +if __name__ == "__main__": warnings.warn("configure_invokeai.py is deprecated, running 'invokeai-configure'...", DeprecationWarning) configure() diff --git a/scripts/controlnet_legacy_txt2img_example.py b/scripts/controlnet_legacy_txt2img_example.py index eb299c9d47..8400cc0290 100644 --- a/scripts/controlnet_legacy_txt2img_example.py +++ b/scripts/controlnet_legacy_txt2img_example.py @@ -28,11 +28,12 @@ canny_image.show() print("loading base model stable-diffusion-1.5") model_config_path = os.getcwd() + "/../configs/models.yaml" model_manager = ModelManager(model_config_path) -model = model_manager.get_model('stable-diffusion-1.5') +model = model_manager.get_model("stable-diffusion-1.5") print("loading control model lllyasviel/sd-controlnet-canny") -canny_controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", - torch_dtype=torch.float16).to("cuda") +canny_controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16).to( + "cuda" +) print("testing Txt2Img() constructor with control_model arg") txt2img_canny = Txt2Img(model, control_model=canny_controlnet) @@ -49,6 +50,3 @@ outputs = txt2img_canny.generate( generate_output = next(outputs) out_image = generate_output.image out_image.show() - - - diff --git a/scripts/dream.py b/scripts/dream.py index 66c7600c6f..12176db41e 100755 --- a/scripts/dream.py +++ b/scripts/dream.py @@ -3,8 +3,9 @@ import warnings from invokeai.frontend.CLI import invokeai_command_line_interface as main -warnings.warn("dream.py is being deprecated, please run invoke.py for the " - "new UI/API or legacy_api.py for the old API", - DeprecationWarning) -main() +warnings.warn( + "dream.py is being deprecated, please run invoke.py for the " "new UI/API or legacy_api.py for the old API", + DeprecationWarning, +) +main() diff --git a/scripts/images2prompt.py b/scripts/images2prompt.py index 625be83482..058fc0da40 100755 --- a/scripts/images2prompt.py +++ b/scripts/images2prompt.py @@ -1,12 +1,14 @@ #!/usr/bin/env python -'''This script reads the "Invoke" Stable Diffusion prompt embedded in files generated by invoke.py''' +"""This script reads the "Invoke" Stable Diffusion prompt embedded in files generated by invoke.py""" import sys -from PIL import Image,PngImagePlugin +from PIL import Image, PngImagePlugin if len(sys.argv) < 2: print("Usage: file2prompt.py ...") - print("This script opens up the indicated invoke.py-generated PNG file(s) and prints out the prompt used to generate them.") + print( + "This script opens up the indicated invoke.py-generated PNG file(s) and prints out the prompt used to generate them." + ) exit(-1) filenames = sys.argv[1:] @@ -14,17 +16,13 @@ for f in filenames: try: im = Image.open(f) try: - prompt = im.text['Dream'] + prompt = im.text["Dream"] except KeyError: - prompt = '' - print(f'{f}: {prompt}') + prompt = "" + print(f"{f}: {prompt}") except FileNotFoundError: - sys.stderr.write(f'{f} not found\n') + sys.stderr.write(f"{f} not found\n") continue except PermissionError: - sys.stderr.write(f'{f} could not be opened due to inadequate permissions\n') + sys.stderr.write(f"{f} could not be opened due to inadequate permissions\n") continue - - - - diff --git a/scripts/invokeai-cli.py b/scripts/invokeai-cli.py index bb67d9d540..b32a892261 100755 --- a/scripts/invokeai-cli.py +++ b/scripts/invokeai-cli.py @@ -3,18 +3,22 @@ # Copyright (c) 2022 Kyle Schouviller (https://github.com/kyle0654) import logging -logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage()) + +logging.getLogger("xformers").addFilter(lambda record: "A matching Triton is not available" not in record.getMessage()) import os import sys + def main(): # Change working directory to the repo root os.chdir(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) # TODO: Parse some top-level args here. from invokeai.app.cli_app import invoke_cli + invoke_cli() -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/scripts/invokeai-model-install.py b/scripts/invokeai-model-install.py index 97bb499812..b4b0dbc8ef 100644 --- a/scripts/invokeai-model-install.py +++ b/scripts/invokeai-model-install.py @@ -1,3 +1,3 @@ from invokeai.frontend.install.model_install import main -main() +main() diff --git a/scripts/invokeai-web.py b/scripts/invokeai-web.py index 9ac7ee5cb9..829cc4b911 100755 --- a/scripts/invokeai-web.py +++ b/scripts/invokeai-web.py @@ -3,18 +3,21 @@ # Copyright (c) 2022 Kyle Schouviller (https://github.com/kyle0654) import logging -logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage()) + +logging.getLogger("xformers").addFilter(lambda record: "A matching Triton is not available" not in record.getMessage()) import os import sys + def main(): # Change working directory to the repo root os.chdir(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) from invokeai.app.api_app import invoke_api + invoke_api() -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/scripts/make_models_markdown_table.py b/scripts/make_models_markdown_table.py index 128ced371d..8e7c528a46 100755 --- a/scripts/make_models_markdown_table.py +++ b/scripts/make_models_markdown_table.py @@ -1,23 +1,24 @@ #!/usr/bin/env python -''' +""" This script is used at release time to generate a markdown table describing the starter models. This text is then manually copied into 050_INSTALL_MODELS.md. -''' +""" from omegaconf import OmegaConf from pathlib import Path def main(): - initial_models_file = Path(__file__).parent / '../invokeai/configs/INITIAL_MODELS.yaml' + initial_models_file = Path(__file__).parent / "../invokeai/configs/INITIAL_MODELS.yaml" models = OmegaConf.load(initial_models_file) - print('|Model Name | HuggingFace Repo ID | Description | URL |') - print('|---------- | ---------- | ----------- | --- |') + print("|Model Name | HuggingFace Repo ID | Description | URL |") + print("|---------- | ---------- | ----------- | --- |") for model in models: repo_id = models[model].repo_id - url = f'https://huggingface.co/{repo_id}' - print(f'|{model}|{repo_id}|{models[model].description}|{url} |') + url = f"https://huggingface.co/{repo_id}" + print(f"|{model}|{repo_id}|{models[model].description}|{url} |") -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/scripts/orig_scripts/img2img.py b/scripts/orig_scripts/img2img.py index 9f74f25bf2..2601bc2562 100644 --- a/scripts/orig_scripts/img2img.py +++ b/scripts/orig_scripts/img2img.py @@ -18,7 +18,7 @@ from pytorch_lightning import seed_everything from ldm.util import instantiate_from_config from ldm.models.diffusion.ddim import DDIMSampler from ldm.models.diffusion.plms import PLMSSampler -from ldm.invoke.devices import choose_torch_device +from ldm.invoke.devices import choose_torch_device def chunk(it, size): @@ -55,7 +55,7 @@ def load_img(path): image = np.array(image).astype(np.float32) / 255.0 image = image[None].transpose(0, 3, 1, 2) image = torch.from_numpy(image) - return 2.*image - 1. + return 2.0 * image - 1.0 def main(): @@ -66,33 +66,24 @@ def main(): type=str, nargs="?", default="a painting of a virus monster playing guitar", - help="the prompt to render" + help="the prompt to render", ) - parser.add_argument( - "--init-img", - type=str, - nargs="?", - help="path to the input image" - ) + parser.add_argument("--init-img", type=str, nargs="?", help="path to the input image") parser.add_argument( - "--outdir", - type=str, - nargs="?", - help="dir to write results to", - default="outputs/img2img-samples" + "--outdir", type=str, nargs="?", help="dir to write results to", default="outputs/img2img-samples" ) parser.add_argument( "--skip_grid", - action='store_true', + action="store_true", help="do not save a grid, only individual samples. Helpful when evaluating lots of samples", ) parser.add_argument( "--skip_save", - action='store_true', + action="store_true", help="do not save indiviual samples. For speed measurements.", ) @@ -105,12 +96,12 @@ def main(): parser.add_argument( "--plms", - action='store_true', + action="store_true", help="use plms sampling", ) parser.add_argument( "--fixed_code", - action='store_true', + action="store_true", help="if enabled, uses the same starting code across all samples ", ) @@ -187,11 +178,7 @@ def main(): help="the seed (for reproducible sampling)", ) parser.add_argument( - "--precision", - type=str, - help="evaluate at this precision", - choices=["full", "autocast"], - default="autocast" + "--precision", type=str, help="evaluate at this precision", choices=["full", "autocast"], default="autocast" ) opt = parser.parse_args() @@ -232,18 +219,18 @@ def main(): assert os.path.isfile(opt.init_img) init_image = load_img(opt.init_img).to(device) - init_image = repeat(init_image, '1 ... -> b ...', b=batch_size) + init_image = repeat(init_image, "1 ... -> b ...", b=batch_size) init_latent = model.get_first_stage_encoding(model.encode_first_stage(init_image)) # move to latent space sampler.make_schedule(ddim_num_steps=opt.ddim_steps, ddim_eta=opt.ddim_eta, verbose=False) - assert 0. <= opt.strength <= 1., 'can only work with strength in [0.0, 1.0]' + assert 0.0 <= opt.strength <= 1.0, "can only work with strength in [0.0, 1.0]" t_enc = int(opt.strength * opt.ddim_steps) print(f"target t_enc is {t_enc} steps") precision_scope = autocast if opt.precision == "autocast" else nullcontext - if device.type in ['mps', 'cpu']: - precision_scope = nullcontext # have to use f32 on mps + if device.type in ["mps", "cpu"]: + precision_scope = nullcontext # have to use f32 on mps with torch.no_grad(): with precision_scope(device.type): with model.ema_scope(): @@ -259,37 +246,42 @@ def main(): c = model.get_learned_conditioning(prompts) # encode (scaled latent) - z_enc = sampler.stochastic_encode(init_latent, torch.tensor([t_enc]*batch_size).to(device)) + z_enc = sampler.stochastic_encode(init_latent, torch.tensor([t_enc] * batch_size).to(device)) # decode it - samples = sampler.decode(z_enc, c, t_enc, unconditional_guidance_scale=opt.scale, - unconditional_conditioning=uc,) + samples = sampler.decode( + z_enc, + c, + t_enc, + unconditional_guidance_scale=opt.scale, + unconditional_conditioning=uc, + ) x_samples = model.decode_first_stage(samples) x_samples = torch.clamp((x_samples + 1.0) / 2.0, min=0.0, max=1.0) if not opt.skip_save: for x_sample in x_samples: - x_sample = 255. * rearrange(x_sample.cpu().numpy(), 'c h w -> h w c') + x_sample = 255.0 * rearrange(x_sample.cpu().numpy(), "c h w -> h w c") Image.fromarray(x_sample.astype(np.uint8)).save( - os.path.join(sample_path, f"{base_count:05}.png")) + os.path.join(sample_path, f"{base_count:05}.png") + ) base_count += 1 all_samples.append(x_samples) if not opt.skip_grid: # additionally, save as grid grid = torch.stack(all_samples, 0) - grid = rearrange(grid, 'n b c h w -> (n b) c h w') + grid = rearrange(grid, "n b c h w -> (n b) c h w") grid = make_grid(grid, nrow=n_rows) # to image - grid = 255. * rearrange(grid, 'c h w -> h w c').cpu().numpy() - Image.fromarray(grid.astype(np.uint8)).save(os.path.join(outpath, f'grid-{grid_count:04}.png')) + grid = 255.0 * rearrange(grid, "c h w -> h w c").cpu().numpy() + Image.fromarray(grid.astype(np.uint8)).save(os.path.join(outpath, f"grid-{grid_count:04}.png")) grid_count += 1 toc = time.time() - print(f"Your samples are ready and waiting for you here: \n{outpath} \n" - f" \nEnjoy.") + print(f"Your samples are ready and waiting for you here: \n{outpath} \n" f" \nEnjoy.") if __name__ == "__main__": diff --git a/scripts/orig_scripts/inpaint.py b/scripts/orig_scripts/inpaint.py index b8245db322..8dfbbfb045 100644 --- a/scripts/orig_scripts/inpaint.py +++ b/scripts/orig_scripts/inpaint.py @@ -8,25 +8,26 @@ from main import instantiate_from_config from ldm.models.diffusion.ddim import DDIMSampler from ldm.invoke.devices import choose_torch_device + def make_batch(image, mask, device): image = np.array(Image.open(image).convert("RGB")) - image = image.astype(np.float32)/255.0 - image = image[None].transpose(0,3,1,2) + image = image.astype(np.float32) / 255.0 + image = image[None].transpose(0, 3, 1, 2) image = torch.from_numpy(image) mask = np.array(Image.open(mask).convert("L")) - mask = mask.astype(np.float32)/255.0 - mask = mask[None,None] + mask = mask.astype(np.float32) / 255.0 + mask = mask[None, None] mask[mask < 0.5] = 0 mask[mask >= 0.5] = 1 mask = torch.from_numpy(mask) - masked_image = (1-mask)*image + masked_image = (1 - mask) * image batch = {"image": image, "mask": mask, "masked_image": masked_image} for k in batch: batch[k] = batch[k].to(device=device) - batch[k] = batch[k]*2.0-1.0 + batch[k] = batch[k] * 2.0 - 1.0 return batch @@ -58,11 +59,10 @@ if __name__ == "__main__": config = OmegaConf.load("models/ldm/inpainting_big/config.yaml") model = instantiate_from_config(config.model) - model.load_state_dict(torch.load("models/ldm/inpainting_big/last.ckpt")["state_dict"], - strict=False) + model.load_state_dict(torch.load("models/ldm/inpainting_big/last.ckpt")["state_dict"], strict=False) - device = choose_torch_device() - model = model.to(device) + device = choose_torch_device() + model = model.to(device) sampler = DDIMSampler(model) os.makedirs(opt.outdir, exist_ok=True) @@ -74,25 +74,19 @@ if __name__ == "__main__": # encode masked image and concat downsampled mask c = model.cond_stage_model.encode(batch["masked_image"]) - cc = torch.nn.functional.interpolate(batch["mask"], - size=c.shape[-2:]) + cc = torch.nn.functional.interpolate(batch["mask"], size=c.shape[-2:]) c = torch.cat((c, cc), dim=1) - shape = (c.shape[1]-1,)+c.shape[2:] - samples_ddim, _ = sampler.sample(S=opt.steps, - conditioning=c, - batch_size=c.shape[0], - shape=shape, - verbose=False) + shape = (c.shape[1] - 1,) + c.shape[2:] + samples_ddim, _ = sampler.sample( + S=opt.steps, conditioning=c, batch_size=c.shape[0], shape=shape, verbose=False + ) x_samples_ddim = model.decode_first_stage(samples_ddim) - image = torch.clamp((batch["image"]+1.0)/2.0, - min=0.0, max=1.0) - mask = torch.clamp((batch["mask"]+1.0)/2.0, - min=0.0, max=1.0) - predicted_image = torch.clamp((x_samples_ddim+1.0)/2.0, - min=0.0, max=1.0) + image = torch.clamp((batch["image"] + 1.0) / 2.0, min=0.0, max=1.0) + mask = torch.clamp((batch["mask"] + 1.0) / 2.0, min=0.0, max=1.0) + predicted_image = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0) - inpainted = (1-mask)*image+mask*predicted_image - inpainted = inpainted.cpu().numpy().transpose(0,2,3,1)[0]*255 + inpainted = (1 - mask) * image + mask * predicted_image + inpainted = inpainted.cpu().numpy().transpose(0, 2, 3, 1)[0] * 255 Image.fromarray(inpainted.astype(np.uint8)).save(outpath) diff --git a/scripts/orig_scripts/knn2img.py b/scripts/orig_scripts/knn2img.py index e6eaaecab5..845613479b 100644 --- a/scripts/orig_scripts/knn2img.py +++ b/scripts/orig_scripts/knn2img.py @@ -59,29 +59,24 @@ def load_model_from_config(config, ckpt, verbose=False): class Searcher(object): - def __init__(self, database, retriever_version='ViT-L/14'): + def __init__(self, database, retriever_version="ViT-L/14"): assert database in DATABASES # self.database = self.load_database(database) self.database_name = database - self.searcher_savedir = f'data/rdm/searchers/{self.database_name}' - self.database_path = f'data/rdm/retrieval_databases/{self.database_name}' + self.searcher_savedir = f"data/rdm/searchers/{self.database_name}" + self.database_path = f"data/rdm/retrieval_databases/{self.database_name}" self.retriever = self.load_retriever(version=retriever_version) - self.database = {'embedding': [], - 'img_id': [], - 'patch_coords': []} + self.database = {"embedding": [], "img_id": [], "patch_coords": []} self.load_database() self.load_searcher() - def train_searcher(self, k, - metric='dot_product', - searcher_savedir=None): - - print('Start training searcher') - searcher = scann.scann_ops_pybind.builder(self.database['embedding'] / - np.linalg.norm(self.database['embedding'], axis=1)[:, np.newaxis], - k, metric) + def train_searcher(self, k, metric="dot_product", searcher_savedir=None): + print("Start training searcher") + searcher = scann.scann_ops_pybind.builder( + self.database["embedding"] / np.linalg.norm(self.database["embedding"], axis=1)[:, np.newaxis], k, metric + ) self.searcher = searcher.score_brute_force().build() - print('Finish training searcher') + print("Finish training searcher") if searcher_savedir is not None: print(f'Save trained searcher under "{searcher_savedir}"') @@ -91,36 +86,40 @@ class Searcher(object): def load_single_file(self, saved_embeddings): compressed = np.load(saved_embeddings) self.database = {key: compressed[key] for key in compressed.files} - print('Finished loading of clip embeddings.') + print("Finished loading of clip embeddings.") def load_multi_files(self, data_archive): out_data = {key: [] for key in self.database} - for d in tqdm(data_archive, desc=f'Loading datapool from {len(data_archive)} individual files.'): + for d in tqdm(data_archive, desc=f"Loading datapool from {len(data_archive)} individual files."): for key in d.files: out_data[key].append(d[key]) return out_data def load_database(self): - print(f'Load saved patch embedding from "{self.database_path}"') - file_content = glob.glob(os.path.join(self.database_path, '*.npz')) + file_content = glob.glob(os.path.join(self.database_path, "*.npz")) if len(file_content) == 1: self.load_single_file(file_content[0]) elif len(file_content) > 1: data = [np.load(f) for f in file_content] - prefetched_data = parallel_data_prefetch(self.load_multi_files, data, - n_proc=min(len(data), cpu_count()), target_data_type='dict') + prefetched_data = parallel_data_prefetch( + self.load_multi_files, data, n_proc=min(len(data), cpu_count()), target_data_type="dict" + ) - self.database = {key: np.concatenate([od[key] for od in prefetched_data], axis=1)[0] for key in - self.database} + self.database = { + key: np.concatenate([od[key] for od in prefetched_data], axis=1)[0] for key in self.database + } else: raise ValueError(f'No npz-files in specified path "{self.database_path}" is this directory existing?') print(f'Finished loading of retrieval database of length {self.database["embedding"].shape[0]}.') - def load_retriever(self, version='ViT-L/14', ): + def load_retriever( + self, + version="ViT-L/14", + ): model = FrozenClipImageEmbedder(model=version) if torch.cuda.is_available(): model.cuda() @@ -128,14 +127,14 @@ class Searcher(object): return model def load_searcher(self): - print(f'load searcher for database {self.database_name} from {self.searcher_savedir}') + print(f"load searcher for database {self.database_name} from {self.searcher_savedir}") self.searcher = scann.scann_ops_pybind.load_searcher(self.searcher_savedir) - print('Finished loading searcher.') + print("Finished loading searcher.") def search(self, x, k): - if self.searcher is None and self.database['embedding'].shape[0] < 2e4: - self.train_searcher(k) # quickly fit searcher on the fly for small databases - assert self.searcher is not None, 'Cannot search with uninitialized searcher' + if self.searcher is None and self.database["embedding"].shape[0] < 2e4: + self.train_searcher(k) # quickly fit searcher on the fly for small databases + assert self.searcher is not None, "Cannot search with uninitialized searcher" if isinstance(x, torch.Tensor): x = x.detach().cpu().numpy() if len(x.shape) == 3: @@ -146,17 +145,19 @@ class Searcher(object): nns, distances = self.searcher.search_batched(query_embeddings, final_num_neighbors=k) end = time.time() - out_embeddings = self.database['embedding'][nns] - out_img_ids = self.database['img_id'][nns] - out_pc = self.database['patch_coords'][nns] + out_embeddings = self.database["embedding"][nns] + out_img_ids = self.database["img_id"][nns] + out_pc = self.database["patch_coords"][nns] - out = {'nn_embeddings': out_embeddings / np.linalg.norm(out_embeddings, axis=-1)[..., np.newaxis], - 'img_ids': out_img_ids, - 'patch_coords': out_pc, - 'queries': x, - 'exec_time': end - start, - 'nns': nns, - 'q_embeddings': query_embeddings} + out = { + "nn_embeddings": out_embeddings / np.linalg.norm(out_embeddings, axis=-1)[..., np.newaxis], + "img_ids": out_img_ids, + "patch_coords": out_pc, + "queries": x, + "exec_time": end - start, + "nns": nns, + "q_embeddings": query_embeddings, + } return out @@ -173,20 +174,16 @@ if __name__ == "__main__": type=str, nargs="?", default="a painting of a virus monster playing guitar", - help="the prompt to render" + help="the prompt to render", ) parser.add_argument( - "--outdir", - type=str, - nargs="?", - help="dir to write results to", - default="outputs/txt2img-samples" + "--outdir", type=str, nargs="?", help="dir to write results to", default="outputs/txt2img-samples" ) parser.add_argument( "--skip_grid", - action='store_true', + action="store_true", help="do not save a grid, only individual samples. Helpful when evaluating lots of samples", ) @@ -206,7 +203,7 @@ if __name__ == "__main__": parser.add_argument( "--plms", - action='store_true', + action="store_true", help="use plms sampling", ) @@ -287,14 +284,14 @@ if __name__ == "__main__": parser.add_argument( "--database", type=str, - default='artbench-surrealism', + default="artbench-surrealism", choices=DATABASES, help="The database used for the search, only applied when --use_neighbors=True", ) parser.add_argument( "--use_neighbors", default=False, - action='store_true', + action="store_true", help="Include neighbors in addition to text prompt for conditioning", ) parser.add_argument( @@ -358,41 +355,43 @@ if __name__ == "__main__": uc = None if searcher is not None: nn_dict = searcher(c, opt.knn) - c = torch.cat([c, torch.from_numpy(nn_dict['nn_embeddings']).cuda()], dim=1) + c = torch.cat([c, torch.from_numpy(nn_dict["nn_embeddings"]).cuda()], dim=1) if opt.scale != 1.0: uc = torch.zeros_like(c) if isinstance(prompts, tuple): prompts = list(prompts) shape = [16, opt.H // 16, opt.W // 16] # note: currently hardcoded for f16 model - samples_ddim, _ = sampler.sample(S=opt.ddim_steps, - conditioning=c, - batch_size=c.shape[0], - shape=shape, - verbose=False, - unconditional_guidance_scale=opt.scale, - unconditional_conditioning=uc, - eta=opt.ddim_eta, - ) + samples_ddim, _ = sampler.sample( + S=opt.ddim_steps, + conditioning=c, + batch_size=c.shape[0], + shape=shape, + verbose=False, + unconditional_guidance_scale=opt.scale, + unconditional_conditioning=uc, + eta=opt.ddim_eta, + ) x_samples_ddim = model.decode_first_stage(samples_ddim) x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0) for x_sample in x_samples_ddim: - x_sample = 255. * rearrange(x_sample.cpu().numpy(), 'c h w -> h w c') + x_sample = 255.0 * rearrange(x_sample.cpu().numpy(), "c h w -> h w c") Image.fromarray(x_sample.astype(np.uint8)).save( - os.path.join(sample_path, f"{base_count:05}.png")) + os.path.join(sample_path, f"{base_count:05}.png") + ) base_count += 1 all_samples.append(x_samples_ddim) if not opt.skip_grid: # additionally, save as grid grid = torch.stack(all_samples, 0) - grid = rearrange(grid, 'n b c h w -> (n b) c h w') + grid = rearrange(grid, "n b c h w -> (n b) c h w") grid = make_grid(grid, nrow=n_rows) # to image - grid = 255. * rearrange(grid, 'c h w -> h w c').cpu().numpy() - Image.fromarray(grid.astype(np.uint8)).save(os.path.join(outpath, f'grid-{grid_count:04}.png')) + grid = 255.0 * rearrange(grid, "c h w -> h w c").cpu().numpy() + Image.fromarray(grid.astype(np.uint8)).save(os.path.join(outpath, f"grid-{grid_count:04}.png")) grid_count += 1 print(f"Your samples are ready and waiting for you here: \n{outpath} \nEnjoy.") diff --git a/scripts/orig_scripts/main.py b/scripts/orig_scripts/main.py index 6a88f84380..8269809fbc 100644 --- a/scripts/orig_scripts/main.py +++ b/scripts/orig_scripts/main.py @@ -25,15 +25,19 @@ from pytorch_lightning.utilities import rank_zero_info from ldm.data.base import Txt2ImgIterableBaseDataset from ldm.util import instantiate_from_config + def fix_func(orig): - if hasattr(torch.backends, 'mps') and torch.backends.mps.is_available(): + if hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): + def new_func(*args, **kw): device = kw.get("device", "mps") - kw["device"]="cpu" + kw["device"] = "cpu" return orig(*args, **kw).to(device) + return new_func return orig + torch.rand = fix_func(torch.rand) torch.rand_like = fix_func(torch.rand_like) torch.randn = fix_func(torch.randn) @@ -43,18 +47,19 @@ torch.randint_like = fix_func(torch.randint_like) torch.bernoulli = fix_func(torch.bernoulli) torch.multinomial = fix_func(torch.multinomial) + def load_model_from_config(config, ckpt, verbose=False): - print(f'Loading model from {ckpt}') - pl_sd = torch.load(ckpt, map_location='cpu') - sd = pl_sd['state_dict'] + print(f"Loading model from {ckpt}") + pl_sd = torch.load(ckpt, map_location="cpu") + sd = pl_sd["state_dict"] config.model.params.ckpt_path = ckpt model = instantiate_from_config(config.model) m, u = model.load_state_dict(sd, strict=False) if len(m) > 0 and verbose: - print('missing keys:') + print("missing keys:") print(m) if len(u) > 0 and verbose: - print('unexpected keys:') + print("unexpected keys:") print(u) if torch.cuda.is_available(): @@ -66,132 +71,130 @@ def get_parser(**parser_kwargs): def str2bool(v): if isinstance(v, bool): return v - if v.lower() in ('yes', 'true', 't', 'y', '1'): + if v.lower() in ("yes", "true", "t", "y", "1"): return True - elif v.lower() in ('no', 'false', 'f', 'n', '0'): + elif v.lower() in ("no", "false", "f", "n", "0"): return False else: - raise argparse.ArgumentTypeError('Boolean value expected.') + raise argparse.ArgumentTypeError("Boolean value expected.") parser = argparse.ArgumentParser(**parser_kwargs) parser.add_argument( - '-n', - '--name', + "-n", + "--name", type=str, const=True, - default='', - nargs='?', - help='postfix for logdir', + default="", + nargs="?", + help="postfix for logdir", ) parser.add_argument( - '-r', - '--resume', + "-r", + "--resume", type=str, const=True, - default='', - nargs='?', - help='resume from logdir or checkpoint in logdir', + default="", + nargs="?", + help="resume from logdir or checkpoint in logdir", ) parser.add_argument( - '-b', - '--base', - nargs='*', - metavar='base_config.yaml', - help='paths to base configs. Loaded from left-to-right. ' - 'Parameters can be overwritten or added with command-line options of the form `--key value`.', + "-b", + "--base", + nargs="*", + metavar="base_config.yaml", + help="paths to base configs. Loaded from left-to-right. " + "Parameters can be overwritten or added with command-line options of the form `--key value`.", default=list(), ) parser.add_argument( - '-t', - '--train', + "-t", + "--train", type=str2bool, const=True, default=False, - nargs='?', - help='train', + nargs="?", + help="train", ) parser.add_argument( - '--no-test', + "--no-test", type=str2bool, const=True, default=False, - nargs='?', - help='disable test', + nargs="?", + help="disable test", ) + parser.add_argument("-p", "--project", help="name of new or path to existing project") parser.add_argument( - '-p', '--project', help='name of new or path to existing project' - ) - parser.add_argument( - '-d', - '--debug', + "-d", + "--debug", type=str2bool, - nargs='?', + nargs="?", const=True, default=False, - help='enable post-mortem debugging', + help="enable post-mortem debugging", ) parser.add_argument( - '-s', - '--seed', + "-s", + "--seed", type=int, default=23, - help='seed for seed_everything', + help="seed for seed_everything", ) parser.add_argument( - '-f', - '--postfix', + "-f", + "--postfix", type=str, - default='', - help='post-postfix for default name', + default="", + help="post-postfix for default name", ) parser.add_argument( - '-l', - '--logdir', + "-l", + "--logdir", type=str, - default='logs', - help='directory for logging dat shit', + default="logs", + help="directory for logging dat shit", ) parser.add_argument( - '--scale_lr', + "--scale_lr", type=str2bool, - nargs='?', + nargs="?", const=True, default=True, - help='scale base-lr by ngpu * batch_size * n_accumulate', + help="scale base-lr by ngpu * batch_size * n_accumulate", ) parser.add_argument( - '--datadir_in_name', + "--datadir_in_name", type=str2bool, - nargs='?', + nargs="?", const=True, default=True, - help='Prepend the final directory in the data_root to the output directory name', + help="Prepend the final directory in the data_root to the output directory name", ) parser.add_argument( - '--actual_resume', + "--actual_resume", type=str, - default='', - help='Path to model to actually resume from', + default="", + help="Path to model to actually resume from", ) parser.add_argument( - '--data_root', + "--data_root", type=str, required=True, - help='Path to directory with training images', + help="Path to directory with training images", ) parser.add_argument( - '--embedding_manager_ckpt', + "--embedding_manager_ckpt", type=str, - default='', - help='Initialize embedding manager from a checkpoint', + default="", + help="Initialize embedding manager from a checkpoint", ) parser.add_argument( - '--init_word', + "--init_word", type=str, - help='Word to use as source for initial token embedding.', + help="Word to use as source for initial token embedding.", ) return parser @@ -226,9 +229,7 @@ def worker_init_fn(_): if isinstance(dataset, Txt2ImgIterableBaseDataset): split_size = dataset.num_records // worker_info.num_workers # reset num_records to the true number to retain reliable length information - dataset.sample_ids = dataset.valid_ids[ - worker_id * split_size : (worker_id + 1) * split_size - ] + dataset.sample_ids = dataset.valid_ids[worker_id * split_size : (worker_id + 1) * split_size] current_id = np.random.choice(len(np.random.get_state()[1]), 1) return np.random.seed(np.random.get_state()[1][current_id] + worker_id) else: @@ -252,25 +253,19 @@ class DataModuleFromConfig(pl.LightningDataModule): super().__init__() self.batch_size = batch_size self.dataset_configs = dict() - self.num_workers = ( - num_workers if num_workers is not None else batch_size * 2 - ) + self.num_workers = num_workers if num_workers is not None else batch_size * 2 self.use_worker_init_fn = use_worker_init_fn if train is not None: - self.dataset_configs['train'] = train + self.dataset_configs["train"] = train self.train_dataloader = self._train_dataloader if validation is not None: - self.dataset_configs['validation'] = validation - self.val_dataloader = partial( - self._val_dataloader, shuffle=shuffle_val_dataloader - ) + self.dataset_configs["validation"] = validation + self.val_dataloader = partial(self._val_dataloader, shuffle=shuffle_val_dataloader) if test is not None: - self.dataset_configs['test'] = test - self.test_dataloader = partial( - self._test_dataloader, shuffle=shuffle_test_loader - ) + self.dataset_configs["test"] = test + self.test_dataloader = partial(self._test_dataloader, shuffle=shuffle_test_loader) if predict is not None: - self.dataset_configs['predict'] = predict + self.dataset_configs["predict"] = predict self.predict_dataloader = self._predict_dataloader self.wrap = wrap @@ -279,24 +274,19 @@ class DataModuleFromConfig(pl.LightningDataModule): instantiate_from_config(data_cfg) def setup(self, stage=None): - self.datasets = dict( - (k, instantiate_from_config(self.dataset_configs[k])) - for k in self.dataset_configs - ) + self.datasets = dict((k, instantiate_from_config(self.dataset_configs[k])) for k in self.dataset_configs) if self.wrap: for k in self.datasets: self.datasets[k] = WrappedDataset(self.datasets[k]) def _train_dataloader(self): - is_iterable_dataset = isinstance( - self.datasets['train'], Txt2ImgIterableBaseDataset - ) + is_iterable_dataset = isinstance(self.datasets["train"], Txt2ImgIterableBaseDataset) if is_iterable_dataset or self.use_worker_init_fn: init_fn = worker_init_fn else: init_fn = None return DataLoader( - self.datasets['train'], + self.datasets["train"], batch_size=self.batch_size, num_workers=self.num_workers, shuffle=False if is_iterable_dataset else True, @@ -304,15 +294,12 @@ class DataModuleFromConfig(pl.LightningDataModule): ) def _val_dataloader(self, shuffle=False): - if ( - isinstance(self.datasets['validation'], Txt2ImgIterableBaseDataset) - or self.use_worker_init_fn - ): + if isinstance(self.datasets["validation"], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn: init_fn = worker_init_fn else: init_fn = None return DataLoader( - self.datasets['validation'], + self.datasets["validation"], batch_size=self.batch_size, num_workers=self.num_workers, worker_init_fn=init_fn, @@ -320,9 +307,7 @@ class DataModuleFromConfig(pl.LightningDataModule): ) def _test_dataloader(self, shuffle=False): - is_iterable_dataset = isinstance( - self.datasets['train'], Txt2ImgIterableBaseDataset - ) + is_iterable_dataset = isinstance(self.datasets["train"], Txt2ImgIterableBaseDataset) if is_iterable_dataset or self.use_worker_init_fn: init_fn = worker_init_fn else: @@ -332,7 +317,7 @@ class DataModuleFromConfig(pl.LightningDataModule): shuffle = shuffle and (not is_iterable_dataset) return DataLoader( - self.datasets['test'], + self.datasets["test"], batch_size=self.batch_size, num_workers=self.num_workers, worker_init_fn=init_fn, @@ -340,15 +325,12 @@ class DataModuleFromConfig(pl.LightningDataModule): ) def _predict_dataloader(self, shuffle=False): - if ( - isinstance(self.datasets['predict'], Txt2ImgIterableBaseDataset) - or self.use_worker_init_fn - ): + if isinstance(self.datasets["predict"], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn: init_fn = worker_init_fn else: init_fn = None return DataLoader( - self.datasets['predict'], + self.datasets["predict"], batch_size=self.batch_size, num_workers=self.num_workers, worker_init_fn=init_fn, @@ -356,9 +338,7 @@ class DataModuleFromConfig(pl.LightningDataModule): class SetupCallback(Callback): - def __init__( - self, resume, now, logdir, ckptdir, cfgdir, config, lightning_config - ): + def __init__(self, resume, now, logdir, ckptdir, cfgdir, config, lightning_config): super().__init__() self.resume = resume self.now = now @@ -370,8 +350,8 @@ class SetupCallback(Callback): def on_keyboard_interrupt(self, trainer, pl_module): if trainer.global_rank == 0: - print('Summoning checkpoint.') - ckpt_path = os.path.join(self.ckptdir, 'last.ckpt') + print("Summoning checkpoint.") + ckpt_path = os.path.join(self.ckptdir, "last.ckpt") trainer.save_checkpoint(ckpt_path) def on_pretrain_routine_start(self, trainer, pl_module): @@ -381,36 +361,31 @@ class SetupCallback(Callback): os.makedirs(self.ckptdir, exist_ok=True) os.makedirs(self.cfgdir, exist_ok=True) - if 'callbacks' in self.lightning_config: - if ( - 'metrics_over_trainsteps_checkpoint' - in self.lightning_config['callbacks'] - ): + if "callbacks" in self.lightning_config: + if "metrics_over_trainsteps_checkpoint" in self.lightning_config["callbacks"]: os.makedirs( - os.path.join(self.ckptdir, 'trainstep_checkpoints'), + os.path.join(self.ckptdir, "trainstep_checkpoints"), exist_ok=True, ) - print('Project config') + print("Project config") print(OmegaConf.to_yaml(self.config)) OmegaConf.save( self.config, - os.path.join(self.cfgdir, '{}-project.yaml'.format(self.now)), + os.path.join(self.cfgdir, "{}-project.yaml".format(self.now)), ) - print('Lightning config') + print("Lightning config") print(OmegaConf.to_yaml(self.lightning_config)) OmegaConf.save( - OmegaConf.create({'lightning': self.lightning_config}), - os.path.join( - self.cfgdir, '{}-lightning.yaml'.format(self.now) - ), + OmegaConf.create({"lightning": self.lightning_config}), + os.path.join(self.cfgdir, "{}-lightning.yaml".format(self.now)), ) else: # ModelCheckpoint callback created log directory --- remove it if not self.resume and os.path.exists(self.logdir): dst, name = os.path.split(self.logdir) - dst = os.path.join(dst, 'child_runs', name) + dst = os.path.join(dst, "child_runs", name) os.makedirs(os.path.split(dst)[0], exist_ok=True) try: os.rename(self.logdir, dst) @@ -435,10 +410,8 @@ class ImageLogger(Callback): self.rescale = rescale self.batch_freq = batch_frequency self.max_images = max_images - self.logger_log_images = { } - self.log_steps = [ - 2**n for n in range(int(np.log2(self.batch_freq)) + 1) - ] + self.logger_log_images = {} + self.log_steps = [2**n for n in range(int(np.log2(self.batch_freq)) + 1)] if not increase_log_steps: self.log_steps = [self.batch_freq] self.clamp = clamp @@ -448,10 +421,8 @@ class ImageLogger(Callback): self.log_first_step = log_first_step @rank_zero_only - def log_local( - self, save_dir, split, images, global_step, current_epoch, batch_idx - ): - root = os.path.join(save_dir, 'images', split) + def log_local(self, save_dir, split, images, global_step, current_epoch, batch_idx): + root = os.path.join(save_dir, "images", split) for k in images: grid = torchvision.utils.make_grid(images[k], nrow=4) if self.rescale: @@ -459,22 +430,16 @@ class ImageLogger(Callback): grid = grid.transpose(0, 1).transpose(1, 2).squeeze(-1) grid = grid.numpy() grid = (grid * 255).astype(np.uint8) - filename = '{}_gs-{:06}_e-{:06}_b-{:06}.png'.format( - k, global_step, current_epoch, batch_idx - ) + filename = "{}_gs-{:06}_e-{:06}_b-{:06}.png".format(k, global_step, current_epoch, batch_idx) path = os.path.join(root, filename) os.makedirs(os.path.split(path)[0], exist_ok=True) Image.fromarray(grid).save(path) - def log_img(self, pl_module, batch, batch_idx, split='train'): - check_idx = ( - batch_idx if self.log_on_batch_idx else pl_module.global_step - ) + def log_img(self, pl_module, batch, batch_idx, split="train"): + check_idx = batch_idx if self.log_on_batch_idx else pl_module.global_step if ( self.check_frequency(check_idx) - and hasattr( # batch_idx % self.batch_freq == 0 - pl_module, 'log_images' - ) + and hasattr(pl_module, "log_images") # batch_idx % self.batch_freq == 0 and callable(pl_module.log_images) and self.max_images > 0 ): @@ -485,9 +450,7 @@ class ImageLogger(Callback): pl_module.eval() with torch.no_grad(): - images = pl_module.log_images( - batch, split=split, **self.log_images_kwargs - ) + images = pl_module.log_images(batch, split=split, **self.log_images_kwargs) for k in images: N = min(images[k].shape[0], self.max_images) @@ -506,18 +469,16 @@ class ImageLogger(Callback): batch_idx, ) - logger_log_images = self.logger_log_images.get( - logger, lambda *args, **kwargs: None - ) + logger_log_images = self.logger_log_images.get(logger, lambda *args, **kwargs: None) logger_log_images(pl_module, images, pl_module.global_step, split) if is_train: pl_module.train() def check_frequency(self, check_idx): - if ( - (check_idx % self.batch_freq) == 0 or (check_idx in self.log_steps) - ) and (check_idx > 0 or self.log_first_step): + if ((check_idx % self.batch_freq) == 0 or (check_idx in self.log_steps)) and ( + check_idx > 0 or self.log_first_step + ): try: self.log_steps.pop(0) except IndexError as e: @@ -526,23 +487,15 @@ class ImageLogger(Callback): return True return False - def on_train_batch_end( - self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx=None - ): - if not self.disabled and ( - pl_module.global_step > 0 or self.log_first_step - ): - self.log_img(pl_module, batch, batch_idx, split='train') + def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx=None): + if not self.disabled and (pl_module.global_step > 0 or self.log_first_step): + self.log_img(pl_module, batch, batch_idx, split="train") - def on_validation_batch_end( - self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx=None - ): + def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx=None): if not self.disabled and pl_module.global_step > 0: - self.log_img(pl_module, batch, batch_idx, split='val') - if hasattr(pl_module, 'calibrate_grad_norm'): - if ( - pl_module.calibrate_grad_norm and batch_idx % 25 == 0 - ) and batch_idx > 0: + self.log_img(pl_module, batch, batch_idx, split="val") + if hasattr(pl_module, "calibrate_grad_norm"): + if (pl_module.calibrate_grad_norm and batch_idx % 25 == 0) and batch_idx > 0: self.log_gradients(trainer, pl_module, batch_idx=batch_idx) @@ -562,19 +515,17 @@ class CUDACallback(Callback): try: epoch_time = trainer.training_type_plugin.reduce(epoch_time) - rank_zero_info(f'Average Epoch time: {epoch_time:.2f} seconds') + rank_zero_info(f"Average Epoch time: {epoch_time:.2f} seconds") if torch.cuda.is_available(): - max_memory = ( - torch.cuda.max_memory_allocated(trainer.root_gpu) / 2**20 - ) + max_memory = torch.cuda.max_memory_allocated(trainer.root_gpu) / 2**20 max_memory = trainer.training_type_plugin.reduce(max_memory) - rank_zero_info(f'Average Peak memory {max_memory:.2f}MiB') + rank_zero_info(f"Average Peak memory {max_memory:.2f}MiB") except AttributeError: pass -class ModeSwapCallback(Callback): +class ModeSwapCallback(Callback): def __init__(self, swap_step=2000): super().__init__() self.is_frozen = False @@ -589,7 +540,8 @@ class ModeSwapCallback(Callback): self.is_frozen = False trainer.optimizers = [pl_module.configure_opt_model()] -if __name__ == '__main__': + +if __name__ == "__main__": # custom parser to specify config files, train, test and debug mode, # postfix, resume. # `--key value` arguments are interpreted as arguments to the trainer. @@ -631,7 +583,7 @@ if __name__ == '__main__': # params: # key: value - now = datetime.datetime.now().strftime('%Y-%m-%dT%H-%M-%S') + now = datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S") # add cwd for convenience and to make classes in this file available when # running as `python main.py` @@ -644,50 +596,47 @@ if __name__ == '__main__': opt, unknown = parser.parse_known_args() if opt.name and opt.resume: raise ValueError( - '-n/--name and -r/--resume cannot be specified both.' - 'If you want to resume training in a new log folder, ' - 'use -n/--name in combination with --resume_from_checkpoint' + "-n/--name and -r/--resume cannot be specified both." + "If you want to resume training in a new log folder, " + "use -n/--name in combination with --resume_from_checkpoint" ) if opt.resume: if not os.path.exists(opt.resume): - raise ValueError('Cannot find {}'.format(opt.resume)) + raise ValueError("Cannot find {}".format(opt.resume)) if os.path.isfile(opt.resume): - paths = opt.resume.split('/') + paths = opt.resume.split("/") # idx = len(paths)-paths[::-1].index("logs")+1 # logdir = "/".join(paths[:idx]) - logdir = '/'.join(paths[:-2]) + logdir = "/".join(paths[:-2]) ckpt = opt.resume else: assert os.path.isdir(opt.resume), opt.resume - logdir = opt.resume.rstrip('/') - ckpt = os.path.join(logdir, 'checkpoints', 'last.ckpt') + logdir = opt.resume.rstrip("/") + ckpt = os.path.join(logdir, "checkpoints", "last.ckpt") opt.resume_from_checkpoint = ckpt - base_configs = sorted( - glob.glob(os.path.join(logdir, 'configs/*.yaml')) - ) + base_configs = sorted(glob.glob(os.path.join(logdir, "configs/*.yaml"))) opt.base = base_configs + opt.base - _tmp = logdir.split('/') + _tmp = logdir.split("/") nowname = _tmp[-1] else: if opt.name: - name = '_' + opt.name + name = "_" + opt.name elif opt.base: cfg_fname = os.path.split(opt.base[0])[-1] cfg_name = os.path.splitext(cfg_fname)[0] - name = '_' + cfg_name + name = "_" + cfg_name else: - name = '' + name = "" if opt.datadir_in_name: now = os.path.basename(os.path.normpath(opt.data_root)) + now - nowname = now + name + opt.postfix logdir = os.path.join(opt.logdir, nowname) - ckptdir = os.path.join(logdir, 'checkpoints') - cfgdir = os.path.join(logdir, 'configs') + ckptdir = os.path.join(logdir, "checkpoints") + cfgdir = os.path.join(logdir, "configs") seed_everything(opt.seed) try: @@ -695,19 +644,19 @@ if __name__ == '__main__': configs = [OmegaConf.load(cfg) for cfg in opt.base] cli = OmegaConf.from_dotlist(unknown) config = OmegaConf.merge(*configs, cli) - lightning_config = config.pop('lightning', OmegaConf.create()) + lightning_config = config.pop("lightning", OmegaConf.create()) # merge trainer cli with config - trainer_config = lightning_config.get('trainer', OmegaConf.create()) + trainer_config = lightning_config.get("trainer", OmegaConf.create()) # default to ddp - trainer_config['accelerator'] = 'auto' + trainer_config["accelerator"] = "auto" for k in nondefault_trainer_args(opt): trainer_config[k] = getattr(opt, k) - if not 'gpus' in trainer_config: - del trainer_config['accelerator'] + if not "gpus" in trainer_config: + del trainer_config["accelerator"] cpu = True else: - gpuinfo = trainer_config['gpus'] - print(f'Running on GPUs {gpuinfo}') + gpuinfo = trainer_config["gpus"] + print(f"Running on GPUs {gpuinfo}") cpu = False trainer_opt = argparse.Namespace(**trainer_config) lightning_config.trainer = trainer_config @@ -715,9 +664,7 @@ if __name__ == '__main__': # model # config.model.params.personalization_config.params.init_word = opt.init_word - config.model.params.personalization_config.params.embedding_manager_ckpt = ( - opt.embedding_manager_ckpt - ) + config.model.params.personalization_config.params.embedding_manager_ckpt = opt.embedding_manager_ckpt if opt.init_word: config.model.params.personalization_config.params.initializer_words = [opt.init_word] @@ -731,142 +678,128 @@ if __name__ == '__main__': trainer_kwargs = dict() # default logger configs - def_logger = 'csv' - def_logger_target = 'CSVLogger' + def_logger = "csv" + def_logger_target = "CSVLogger" default_logger_cfgs = { - 'wandb': { - 'target': 'pytorch_lightning.loggers.WandbLogger', - 'params': { - 'name': nowname, - 'save_dir': logdir, - 'offline': opt.debug, - 'id': nowname, + "wandb": { + "target": "pytorch_lightning.loggers.WandbLogger", + "params": { + "name": nowname, + "save_dir": logdir, + "offline": opt.debug, + "id": nowname, }, }, def_logger: { - 'target': 'pytorch_lightning.loggers.' + def_logger_target, - 'params': { - 'name': def_logger, - 'save_dir': logdir, + "target": "pytorch_lightning.loggers." + def_logger_target, + "params": { + "name": def_logger, + "save_dir": logdir, }, }, } default_logger_cfg = default_logger_cfgs[def_logger] - if 'logger' in lightning_config: + if "logger" in lightning_config: logger_cfg = lightning_config.logger else: logger_cfg = OmegaConf.create() logger_cfg = OmegaConf.merge(default_logger_cfg, logger_cfg) - trainer_kwargs['logger'] = instantiate_from_config(logger_cfg) + trainer_kwargs["logger"] = instantiate_from_config(logger_cfg) # modelcheckpoint - use TrainResult/EvalResult(checkpoint_on=metric) to # specify which metric is used to determine best models default_modelckpt_cfg = { - 'target': 'pytorch_lightning.callbacks.ModelCheckpoint', - 'params': { - 'dirpath': ckptdir, - 'filename': '{epoch:06}', - 'verbose': True, - 'save_last': True, + "target": "pytorch_lightning.callbacks.ModelCheckpoint", + "params": { + "dirpath": ckptdir, + "filename": "{epoch:06}", + "verbose": True, + "save_last": True, }, } - if hasattr(model, 'monitor'): - print(f'Monitoring {model.monitor} as checkpoint metric.') - default_modelckpt_cfg['params']['monitor'] = model.monitor - default_modelckpt_cfg['params']['save_top_k'] = 1 + if hasattr(model, "monitor"): + print(f"Monitoring {model.monitor} as checkpoint metric.") + default_modelckpt_cfg["params"]["monitor"] = model.monitor + default_modelckpt_cfg["params"]["save_top_k"] = 1 - if 'modelcheckpoint' in lightning_config: + if "modelcheckpoint" in lightning_config: modelckpt_cfg = lightning_config.modelcheckpoint else: modelckpt_cfg = OmegaConf.create() modelckpt_cfg = OmegaConf.merge(default_modelckpt_cfg, modelckpt_cfg) - print(f'Merged modelckpt-cfg: \n{modelckpt_cfg}') - if version.parse(pl.__version__) < version.parse('1.4.0'): - trainer_kwargs['checkpoint_callback'] = instantiate_from_config( - modelckpt_cfg - ) + print(f"Merged modelckpt-cfg: \n{modelckpt_cfg}") + if version.parse(pl.__version__) < version.parse("1.4.0"): + trainer_kwargs["checkpoint_callback"] = instantiate_from_config(modelckpt_cfg) # add callback which sets up log directory default_callbacks_cfg = { - 'setup_callback': { - 'target': 'main.SetupCallback', - 'params': { - 'resume': opt.resume, - 'now': now, - 'logdir': logdir, - 'ckptdir': ckptdir, - 'cfgdir': cfgdir, - 'config': config, - 'lightning_config': lightning_config, + "setup_callback": { + "target": "main.SetupCallback", + "params": { + "resume": opt.resume, + "now": now, + "logdir": logdir, + "ckptdir": ckptdir, + "cfgdir": cfgdir, + "config": config, + "lightning_config": lightning_config, }, }, - 'image_logger': { - 'target': 'main.ImageLogger', - 'params': { - 'batch_frequency': 750, - 'max_images': 4, - 'clamp': True, + "image_logger": { + "target": "main.ImageLogger", + "params": { + "batch_frequency": 750, + "max_images": 4, + "clamp": True, }, }, - 'learning_rate_logger': { - 'target': 'main.LearningRateMonitor', - 'params': { - 'logging_interval': 'step', + "learning_rate_logger": { + "target": "main.LearningRateMonitor", + "params": { + "logging_interval": "step", # "log_momentum": True }, }, - 'cuda_callback': {'target': 'main.CUDACallback'}, + "cuda_callback": {"target": "main.CUDACallback"}, } - if version.parse(pl.__version__) >= version.parse('1.4.0'): - default_callbacks_cfg.update( - {'checkpoint_callback': modelckpt_cfg} - ) + if version.parse(pl.__version__) >= version.parse("1.4.0"): + default_callbacks_cfg.update({"checkpoint_callback": modelckpt_cfg}) - if 'callbacks' in lightning_config: + if "callbacks" in lightning_config: callbacks_cfg = lightning_config.callbacks else: callbacks_cfg = OmegaConf.create() - if 'metrics_over_trainsteps_checkpoint' in callbacks_cfg: + if "metrics_over_trainsteps_checkpoint" in callbacks_cfg: print( - 'Caution: Saving checkpoints every n train steps without deleting. This might require some free space.' + "Caution: Saving checkpoints every n train steps without deleting. This might require some free space." ) default_metrics_over_trainsteps_ckpt_dict = { - 'metrics_over_trainsteps_checkpoint': { - 'target': 'pytorch_lightning.callbacks.ModelCheckpoint', - 'params': { - 'dirpath': os.path.join( - ckptdir, 'trainstep_checkpoints' - ), - 'filename': '{epoch:06}-{step:09}', - 'verbose': True, - 'save_top_k': -1, - 'every_n_train_steps': 10000, - 'save_weights_only': True, + "metrics_over_trainsteps_checkpoint": { + "target": "pytorch_lightning.callbacks.ModelCheckpoint", + "params": { + "dirpath": os.path.join(ckptdir, "trainstep_checkpoints"), + "filename": "{epoch:06}-{step:09}", + "verbose": True, + "save_top_k": -1, + "every_n_train_steps": 10000, + "save_weights_only": True, }, } } - default_callbacks_cfg.update( - default_metrics_over_trainsteps_ckpt_dict - ) + default_callbacks_cfg.update(default_metrics_over_trainsteps_ckpt_dict) callbacks_cfg = OmegaConf.merge(default_callbacks_cfg, callbacks_cfg) - if 'ignore_keys_callback' in callbacks_cfg and hasattr( - trainer_opt, 'resume_from_checkpoint' - ): - callbacks_cfg.ignore_keys_callback.params[ - 'ckpt_path' - ] = trainer_opt.resume_from_checkpoint - elif 'ignore_keys_callback' in callbacks_cfg: - del callbacks_cfg['ignore_keys_callback'] + if "ignore_keys_callback" in callbacks_cfg and hasattr(trainer_opt, "resume_from_checkpoint"): + callbacks_cfg.ignore_keys_callback.params["ckpt_path"] = trainer_opt.resume_from_checkpoint + elif "ignore_keys_callback" in callbacks_cfg: + del callbacks_cfg["ignore_keys_callback"] - trainer_kwargs['callbacks'] = [ - instantiate_from_config(callbacks_cfg[k]) for k in callbacks_cfg - ] - trainer_kwargs['max_steps'] = trainer_opt.max_steps + trainer_kwargs["callbacks"] = [instantiate_from_config(callbacks_cfg[k]) for k in callbacks_cfg] + trainer_kwargs["max_steps"] = trainer_opt.max_steps - if hasattr(torch.backends, 'mps') and torch.backends.mps.is_available(): - trainer_opt.accelerator = 'mps' + if hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): + trainer_opt.accelerator = "mps" trainer_opt.detect_anomaly = False trainer = Trainer.from_argparse_args(trainer_opt, **trainer_kwargs) @@ -882,11 +815,9 @@ if __name__ == '__main__': # lightning still takes care of proper multiprocessing though data.prepare_data() data.setup() - print('#### Data #####') + print("#### Data #####") for k in data.datasets: - print( - f'{k}, {data.datasets[k].__class__.__name__}, {len(data.datasets[k])}' - ) + print(f"{k}, {data.datasets[k].__class__.__name__}, {len(data.datasets[k])}") # configure learning rate bs, base_lr = ( @@ -894,24 +825,20 @@ if __name__ == '__main__': config.model.base_learning_rate, ) if not cpu: - gpus = str(lightning_config.trainer.gpus).strip(', ').split(',') + gpus = str(lightning_config.trainer.gpus).strip(", ").split(",") ngpu = len(gpus) else: ngpu = 1 - if 'accumulate_grad_batches' in lightning_config.trainer: - accumulate_grad_batches = ( - lightning_config.trainer.accumulate_grad_batches - ) + if "accumulate_grad_batches" in lightning_config.trainer: + accumulate_grad_batches = lightning_config.trainer.accumulate_grad_batches else: accumulate_grad_batches = 1 - print(f'accumulate_grad_batches = {accumulate_grad_batches}') - lightning_config.trainer.accumulate_grad_batches = ( - accumulate_grad_batches - ) + print(f"accumulate_grad_batches = {accumulate_grad_batches}") + lightning_config.trainer.accumulate_grad_batches = accumulate_grad_batches if opt.scale_lr: model.learning_rate = accumulate_grad_batches * ngpu * bs * base_lr print( - 'Setting learning rate to {:.2e} = {} (accumulate_grad_batches) * {} (num_gpus) * {} (batchsize) * {:.2e} (base_lr)'.format( + "Setting learning rate to {:.2e} = {} (accumulate_grad_batches) * {} (num_gpus) * {} (batchsize) * {:.2e} (base_lr)".format( model.learning_rate, accumulate_grad_batches, ngpu, @@ -921,15 +848,15 @@ if __name__ == '__main__': ) else: model.learning_rate = base_lr - print('++++ NOT USING LR SCALING ++++') - print(f'Setting learning rate to {model.learning_rate:.2e}') + print("++++ NOT USING LR SCALING ++++") + print(f"Setting learning rate to {model.learning_rate:.2e}") # allow checkpointing via USR1 def melk(*args, **kwargs): # run all checkpoint hooks if trainer.global_rank == 0: - print('Summoning checkpoint.') - ckpt_path = os.path.join(ckptdir, 'last.ckpt') + print("Summoning checkpoint.") + ckpt_path = os.path.join(ckptdir, "last.ckpt") trainer.save_checkpoint(ckpt_path) def divein(*args, **kwargs): @@ -964,7 +891,7 @@ if __name__ == '__main__': # move newly created debug project to debug_runs if opt.debug and not opt.resume and trainer.global_rank == 0: dst, name = os.path.split(logdir) - dst = os.path.join(dst, 'debug_runs', name) + dst = os.path.join(dst, "debug_runs", name) os.makedirs(os.path.split(dst)[0], exist_ok=True) os.rename(logdir, dst) # if trainer.global_rank == 0: diff --git a/scripts/orig_scripts/merge_embeddings.py b/scripts/orig_scripts/merge_embeddings.py index 97e72f9128..c2cf1acb1a 100755 --- a/scripts/orig_scripts/merge_embeddings.py +++ b/scripts/orig_scripts/merge_embeddings.py @@ -7,21 +7,30 @@ from functools import partial import torch -def get_placeholder_loop(placeholder_string, embedder, use_bert): - new_placeholder = None +def get_placeholder_loop(placeholder_string, embedder, use_bert): + new_placeholder = None while True: if new_placeholder is None: - new_placeholder = input(f"Placeholder string {placeholder_string} was already used. Please enter a replacement string: ") + new_placeholder = input( + f"Placeholder string {placeholder_string} was already used. Please enter a replacement string: " + ) else: - new_placeholder = input(f"Placeholder string '{new_placeholder}' maps to more than a single token. Please enter another string: ") + new_placeholder = input( + f"Placeholder string '{new_placeholder}' maps to more than a single token. Please enter another string: " + ) - token = get_bert_token_for_string(embedder.tknz_fn, new_placeholder) if use_bert else get_clip_token_for_string(embedder.tokenizer, new_placeholder) + token = ( + get_bert_token_for_string(embedder.tknz_fn, new_placeholder) + if use_bert + else get_clip_token_for_string(embedder.tokenizer, new_placeholder) + ) if token is not None: return new_placeholder, token + def get_clip_token_for_string(tokenizer, string): batch_encoding = tokenizer( string, @@ -30,7 +39,7 @@ def get_clip_token_for_string(tokenizer, string): return_length=True, return_overflowing_tokens=False, padding="max_length", - return_tensors="pt" + return_tensors="pt", ) tokens = batch_encoding["input_ids"] @@ -40,6 +49,7 @@ def get_clip_token_for_string(tokenizer, string): return None + def get_bert_token_for_string(tokenizer, string): token = tokenizer(string) if torch.count_nonzero(token) == 3: @@ -49,22 +59,17 @@ def get_bert_token_for_string(tokenizer, string): if __name__ == "__main__": - parser = argparse.ArgumentParser() parser.add_argument( "--root_dir", type=str, - default='.', - help="Path to the InvokeAI install directory containing 'models', 'outputs' and 'configs'." + default=".", + help="Path to the InvokeAI install directory containing 'models', 'outputs' and 'configs'.", ) parser.add_argument( - "--manager_ckpts", - type=str, - nargs="+", - required=True, - help="Paths to a set of embedding managers to be merged." + "--manager_ckpts", type=str, nargs="+", required=True, help="Paths to a set of embedding managers to be merged." ) parser.add_argument( @@ -75,13 +80,14 @@ if __name__ == "__main__": ) parser.add_argument( - "-sd", "--use_bert", + "-sd", + "--use_bert", action="store_true", - help="Flag to denote that we are not merging stable diffusion embeddings" + help="Flag to denote that we are not merging stable diffusion embeddings", ) args = parser.parse_args() - Globals.root=args.root_dir + Globals.root = args.root_dir if args.use_bert: embedder = BERTEmbedder(n_embed=1280, n_layer=32).cuda() diff --git a/scripts/orig_scripts/sample_diffusion.py b/scripts/orig_scripts/sample_diffusion.py index 876fe3c364..9f08b6702a 100644 --- a/scripts/orig_scripts/sample_diffusion.py +++ b/scripts/orig_scripts/sample_diffusion.py @@ -10,12 +10,13 @@ from PIL import Image from ldm.models.diffusion.ddim import DDIMSampler from ldm.util import instantiate_from_config -rescale = lambda x: (x + 1.) / 2. +rescale = lambda x: (x + 1.0) / 2.0 + def custom_to_pil(x): x = x.detach().cpu() - x = torch.clamp(x, -1., 1.) - x = (x + 1.) / 2. + x = torch.clamp(x, -1.0, 1.0) + x = (x + 1.0) / 2.0 x = x.permute(1, 2, 0).numpy() x = (255 * x).astype(np.uint8) x = Image.fromarray(x) @@ -51,49 +52,51 @@ def logs2pil(logs, keys=["sample"]): @torch.no_grad() -def convsample(model, shape, return_intermediates=True, - verbose=True, - make_prog_row=False): - - +def convsample(model, shape, return_intermediates=True, verbose=True, make_prog_row=False): if not make_prog_row: - return model.p_sample_loop(None, shape, - return_intermediates=return_intermediates, verbose=verbose) + return model.p_sample_loop(None, shape, return_intermediates=return_intermediates, verbose=verbose) else: - return model.progressive_denoising( - None, shape, verbose=True - ) + return model.progressive_denoising(None, shape, verbose=True) @torch.no_grad() -def convsample_ddim(model, steps, shape, eta=1.0 - ): +def convsample_ddim(model, steps, shape, eta=1.0): ddim = DDIMSampler(model) bs = shape[0] shape = shape[1:] - samples, intermediates = ddim.sample(steps, batch_size=bs, shape=shape, eta=eta, verbose=False,) + samples, intermediates = ddim.sample( + steps, + batch_size=bs, + shape=shape, + eta=eta, + verbose=False, + ) return samples, intermediates @torch.no_grad() -def make_convolutional_sample(model, batch_size, vanilla=False, custom_steps=None, eta=1.0,): - - +def make_convolutional_sample( + model, + batch_size, + vanilla=False, + custom_steps=None, + eta=1.0, +): log = dict() - shape = [batch_size, - model.model.diffusion_model.in_channels, - model.model.diffusion_model.image_size, - model.model.diffusion_model.image_size] + shape = [ + batch_size, + model.model.diffusion_model.in_channels, + model.model.diffusion_model.image_size, + model.model.diffusion_model.image_size, + ] with model.ema_scope("Plotting"): t0 = time.time() if vanilla: - sample, progrow = convsample(model, shape, - make_prog_row=True) + sample, progrow = convsample(model, shape, make_prog_row=True) else: - sample, intermediates = convsample_ddim(model, steps=custom_steps, shape=shape, - eta=eta) + sample, intermediates = convsample_ddim(model, steps=custom_steps, shape=shape, eta=eta) t1 = time.time() @@ -101,32 +104,32 @@ def make_convolutional_sample(model, batch_size, vanilla=False, custom_steps=Non log["sample"] = x_sample log["time"] = t1 - t0 - log['throughput'] = sample.shape[0] / (t1 - t0) + log["throughput"] = sample.shape[0] / (t1 - t0) print(f'Throughput for this batch: {log["throughput"]}') return log + def run(model, logdir, batch_size=50, vanilla=False, custom_steps=None, eta=None, n_samples=50000, nplog=None): if vanilla: - print(f'Using Vanilla DDPM sampling with {model.num_timesteps} sampling steps.') + print(f"Using Vanilla DDPM sampling with {model.num_timesteps} sampling steps.") else: - print(f'Using DDIM sampling with {custom_steps} sampling steps and eta={eta}') - + print(f"Using DDIM sampling with {custom_steps} sampling steps and eta={eta}") tstart = time.time() - n_saved = len(glob.glob(os.path.join(logdir,'*.png')))-1 + n_saved = len(glob.glob(os.path.join(logdir, "*.png"))) - 1 # path = logdir if model.cond_stage_model is None: all_images = [] print(f"Running unconditional sampling for {n_samples} samples") for _ in trange(n_samples // batch_size, desc="Sampling Batches (unconditional)"): - logs = make_convolutional_sample(model, batch_size=batch_size, - vanilla=vanilla, custom_steps=custom_steps, - eta=eta) + logs = make_convolutional_sample( + model, batch_size=batch_size, vanilla=vanilla, custom_steps=custom_steps, eta=eta + ) n_saved = save_logs(logs, logdir, n_saved=n_saved, key="sample") all_images.extend([custom_to_np(logs["sample"])]) if n_saved >= n_samples: - print(f'Finish after generating {n_saved} samples') + print(f"Finish after generating {n_saved} samples") break all_img = np.concatenate(all_images, axis=0) all_img = all_img[:n_samples] @@ -135,7 +138,7 @@ def run(model, logdir, batch_size=50, vanilla=False, custom_steps=None, eta=None np.savez(nppath, all_img) else: - raise NotImplementedError('Currently only sampling for unconditional models supported.') + raise NotImplementedError("Currently only sampling for unconditional models supported.") print(f"sampling of {n_saved} images finished in {(time.time() - tstart) / 60.:.2f} minutes.") @@ -168,58 +171,33 @@ def get_parser(): nargs="?", help="load from logdir or checkpoint in logdir", ) - parser.add_argument( - "-n", - "--n_samples", - type=int, - nargs="?", - help="number of samples to draw", - default=50000 - ) + parser.add_argument("-n", "--n_samples", type=int, nargs="?", help="number of samples to draw", default=50000) parser.add_argument( "-e", "--eta", type=float, nargs="?", help="eta for ddim sampling (0.0 yields deterministic sampling)", - default=1.0 + default=1.0, ) parser.add_argument( "-v", "--vanilla_sample", default=False, - action='store_true', + action="store_true", help="vanilla sampling (default option is DDIM sampling)?", ) + parser.add_argument("-l", "--logdir", type=str, nargs="?", help="extra logdir", default="none") parser.add_argument( - "-l", - "--logdir", - type=str, - nargs="?", - help="extra logdir", - default="none" - ) - parser.add_argument( - "-c", - "--custom_steps", - type=int, - nargs="?", - help="number of steps for ddim and fastdpm sampling", - default=50 - ) - parser.add_argument( - "--batch_size", - type=int, - nargs="?", - help="the bs", - default=10 + "-c", "--custom_steps", type=int, nargs="?", help="number of steps for ddim and fastdpm sampling", default=50 ) + parser.add_argument("--batch_size", type=int, nargs="?", help="the bs", default=10) return parser def load_model_from_config(config, sd): model = instantiate_from_config(config) - model.load_state_dict(sd,strict=False) + model.load_state_dict(sd, strict=False) model.cuda() model.eval() return model @@ -233,8 +211,7 @@ def load_model(config, ckpt, gpu, eval_mode): else: pl_sd = {"state_dict": None} global_step = None - model = load_model_from_config(config.model, - pl_sd["state_dict"]) + model = load_model_from_config(config.model, pl_sd["state_dict"]) return model, global_step @@ -253,9 +230,9 @@ if __name__ == "__main__": if os.path.isfile(opt.resume): # paths = opt.resume.split("/") try: - logdir = '/'.join(opt.resume.split('/')[:-1]) + logdir = "/".join(opt.resume.split("/")[:-1]) # idx = len(paths)-paths[::-1].index("logs")+1 - print(f'Logdir is {logdir}') + print(f"Logdir is {logdir}") except ValueError: paths = opt.resume.split("/") idx = -2 # take a guess: path/to/logdir/checkpoints/model.ckpt @@ -278,7 +255,8 @@ if __name__ == "__main__": if opt.logdir != "none": locallog = logdir.split(os.sep)[-1] - if locallog == "": locallog = logdir.split(os.sep)[-2] + if locallog == "": + locallog = logdir.split(os.sep)[-2] print(f"Switching logdir from '{logdir}' to '{os.path.join(opt.logdir, locallog)}'") logdir = os.path.join(opt.logdir, locallog) @@ -301,13 +279,19 @@ if __name__ == "__main__": sampling_file = os.path.join(logdir, "sampling_config.yaml") sampling_conf = vars(opt) - with open(sampling_file, 'w') as f: + with open(sampling_file, "w") as f: yaml.dump(sampling_conf, f, default_flow_style=False) print(sampling_conf) - - run(model, imglogdir, eta=opt.eta, - vanilla=opt.vanilla_sample, n_samples=opt.n_samples, custom_steps=opt.custom_steps, - batch_size=opt.batch_size, nplog=numpylogdir) + run( + model, + imglogdir, + eta=opt.eta, + vanilla=opt.vanilla_sample, + n_samples=opt.n_samples, + custom_steps=opt.custom_steps, + batch_size=opt.batch_size, + nplog=numpylogdir, + ) print("done.") diff --git a/scripts/orig_scripts/train_searcher.py b/scripts/orig_scripts/train_searcher.py index 1e7904889c..7ba57f1165 100644 --- a/scripts/orig_scripts/train_searcher.py +++ b/scripts/orig_scripts/train_searcher.py @@ -13,21 +13,26 @@ def search_bruteforce(searcher): return searcher.score_brute_force().build() -def search_partioned_ah(searcher, dims_per_block, aiq_threshold, reorder_k, - partioning_trainsize, num_leaves, num_leaves_to_search): - return searcher.tree(num_leaves=num_leaves, - num_leaves_to_search=num_leaves_to_search, - training_sample_size=partioning_trainsize). \ - score_ah(dims_per_block, anisotropic_quantization_threshold=aiq_threshold).reorder(reorder_k).build() +def search_partioned_ah( + searcher, dims_per_block, aiq_threshold, reorder_k, partioning_trainsize, num_leaves, num_leaves_to_search +): + return ( + searcher.tree( + num_leaves=num_leaves, num_leaves_to_search=num_leaves_to_search, training_sample_size=partioning_trainsize + ) + .score_ah(dims_per_block, anisotropic_quantization_threshold=aiq_threshold) + .reorder(reorder_k) + .build() + ) def search_ah(searcher, dims_per_block, aiq_threshold, reorder_k): - return searcher.score_ah(dims_per_block, anisotropic_quantization_threshold=aiq_threshold).reorder( - reorder_k).build() + return ( + searcher.score_ah(dims_per_block, anisotropic_quantization_threshold=aiq_threshold).reorder(reorder_k).build() + ) + def load_datapool(dpath): - - def load_single_file(saved_embeddings): compressed = np.load(saved_embeddings) database = {key: compressed[key] for key in compressed.files} @@ -35,23 +40,26 @@ def load_datapool(dpath): def load_multi_files(data_archive): database = {key: [] for key in data_archive[0].files} - for d in tqdm(data_archive, desc=f'Loading datapool from {len(data_archive)} individual files.'): + for d in tqdm(data_archive, desc=f"Loading datapool from {len(data_archive)} individual files."): for key in d.files: database[key].append(d[key]) return database print(f'Load saved patch embedding from "{dpath}"') - file_content = glob.glob(os.path.join(dpath, '*.npz')) + file_content = glob.glob(os.path.join(dpath, "*.npz")) if len(file_content) == 1: data_pool = load_single_file(file_content[0]) elif len(file_content) > 1: data = [np.load(f) for f in file_content] - prefetched_data = parallel_data_prefetch(load_multi_files, data, - n_proc=min(len(data), cpu_count()), target_data_type='dict') + prefetched_data = parallel_data_prefetch( + load_multi_files, data, n_proc=min(len(data), cpu_count()), target_data_type="dict" + ) - data_pool = {key: np.concatenate([od[key] for od in prefetched_data], axis=1)[0] for key in prefetched_data[0].keys()} + data_pool = { + key: np.concatenate([od[key] for od in prefetched_data], axis=1)[0] for key in prefetched_data[0].keys() + } else: raise ValueError(f'No npz-files in specified path "{dpath}" is this directory existing?') @@ -59,16 +67,17 @@ def load_datapool(dpath): return data_pool -def train_searcher(opt, - metric='dot_product', - partioning_trainsize=None, - reorder_k=None, - # todo tune - aiq_thld=0.2, - dims_per_block=2, - num_leaves=None, - num_leaves_to_search=None,): - +def train_searcher( + opt, + metric="dot_product", + partioning_trainsize=None, + reorder_k=None, + # todo tune + aiq_thld=0.2, + dims_per_block=2, + num_leaves=None, + num_leaves_to_search=None, +): data_pool = load_datapool(opt.database) k = opt.knn @@ -77,71 +86,83 @@ def train_searcher(opt, # normalize # embeddings = - searcher = scann.scann_ops_pybind.builder(data_pool['embedding'] / np.linalg.norm(data_pool['embedding'], axis=1)[:, np.newaxis], k, metric) - pool_size = data_pool['embedding'].shape[0] + searcher = scann.scann_ops_pybind.builder( + data_pool["embedding"] / np.linalg.norm(data_pool["embedding"], axis=1)[:, np.newaxis], k, metric + ) + pool_size = data_pool["embedding"].shape[0] - print(*(['#'] * 100)) - print('Initializing scaNN searcher with the following values:') - print(f'k: {k}') - print(f'metric: {metric}') - print(f'reorder_k: {reorder_k}') - print(f'anisotropic_quantization_threshold: {aiq_thld}') - print(f'dims_per_block: {dims_per_block}') - print(*(['#'] * 100)) - print('Start training searcher....') - print(f'N samples in pool is {pool_size}') + print(*(["#"] * 100)) + print("Initializing scaNN searcher with the following values:") + print(f"k: {k}") + print(f"metric: {metric}") + print(f"reorder_k: {reorder_k}") + print(f"anisotropic_quantization_threshold: {aiq_thld}") + print(f"dims_per_block: {dims_per_block}") + print(*(["#"] * 100)) + print("Start training searcher....") + print(f"N samples in pool is {pool_size}") # this reflects the recommended design choices proposed at # https://github.com/google-research/google-research/blob/aca5f2e44e301af172590bb8e65711f0c9ee0cfd/scann/docs/algorithms.md if pool_size < 2e4: - print('Using brute force search.') + print("Using brute force search.") searcher = search_bruteforce(searcher) elif 2e4 <= pool_size and pool_size < 1e5: - print('Using asymmetric hashing search and reordering.') + print("Using asymmetric hashing search and reordering.") searcher = search_ah(searcher, dims_per_block, aiq_thld, reorder_k) else: - print('Using using partioning, asymmetric hashing search and reordering.') + print("Using using partioning, asymmetric hashing search and reordering.") if not partioning_trainsize: - partioning_trainsize = data_pool['embedding'].shape[0] // 10 + partioning_trainsize = data_pool["embedding"].shape[0] // 10 if not num_leaves: num_leaves = int(np.sqrt(pool_size)) if not num_leaves_to_search: num_leaves_to_search = max(num_leaves // 20, 1) - print('Partitioning params:') - print(f'num_leaves: {num_leaves}') - print(f'num_leaves_to_search: {num_leaves_to_search}') + print("Partitioning params:") + print(f"num_leaves: {num_leaves}") + print(f"num_leaves_to_search: {num_leaves_to_search}") # self.searcher = self.search_ah(searcher, dims_per_block, aiq_thld, reorder_k) - searcher = search_partioned_ah(searcher, dims_per_block, aiq_thld, reorder_k, - partioning_trainsize, num_leaves, num_leaves_to_search) + searcher = search_partioned_ah( + searcher, dims_per_block, aiq_thld, reorder_k, partioning_trainsize, num_leaves, num_leaves_to_search + ) - print('Finish training searcher') + print("Finish training searcher") searcher_savedir = opt.target_path os.makedirs(searcher_savedir, exist_ok=True) searcher.serialize(searcher_savedir) print(f'Saved trained searcher under "{searcher_savedir}"') -if __name__ == '__main__': + +if __name__ == "__main__": sys.path.append(os.getcwd()) parser = argparse.ArgumentParser() - parser.add_argument('--database', - '-d', - default='data/rdm/retrieval_databases/openimages', - type=str, - help='path to folder containing the clip feature of the database') - parser.add_argument('--target_path', - '-t', - default='data/rdm/searchers/openimages', - type=str, - help='path to the target folder where the searcher shall be stored.') - parser.add_argument('--knn', - '-k', - default=20, - type=int, - help='number of nearest neighbors, for which the searcher shall be optimized') + parser.add_argument( + "--database", + "-d", + default="data/rdm/retrieval_databases/openimages", + type=str, + help="path to folder containing the clip feature of the database", + ) + parser.add_argument( + "--target_path", + "-t", + default="data/rdm/searchers/openimages", + type=str, + help="path to the target folder where the searcher shall be stored.", + ) + parser.add_argument( + "--knn", + "-k", + default=20, + type=int, + help="number of nearest neighbors, for which the searcher shall be optimized", + ) - opt, _ = parser.parse_known_args() + opt, _ = parser.parse_known_args() - train_searcher(opt,) \ No newline at end of file + train_searcher( + opt, + ) diff --git a/scripts/orig_scripts/txt2img.py b/scripts/orig_scripts/txt2img.py index 0d350d2c73..58767c122d 100644 --- a/scripts/orig_scripts/txt2img.py +++ b/scripts/orig_scripts/txt2img.py @@ -15,10 +15,11 @@ from contextlib import contextmanager, nullcontext import k_diffusion as K import torch.nn as nn -from ldm.util import instantiate_from_config +from ldm.util import instantiate_from_config from ldm.models.diffusion.ddim import DDIMSampler from ldm.models.diffusion.plms import PLMSSampler -from ldm.invoke.devices import choose_torch_device +from ldm.invoke.devices import choose_torch_device + def chunk(it, size): it = iter(it) @@ -53,23 +54,19 @@ def main(): type=str, nargs="?", default="a painting of a virus monster playing guitar", - help="the prompt to render" + help="the prompt to render", ) parser.add_argument( - "--outdir", - type=str, - nargs="?", - help="dir to write results to", - default="outputs/txt2img-samples" + "--outdir", type=str, nargs="?", help="dir to write results to", default="outputs/txt2img-samples" ) parser.add_argument( "--skip_grid", - action='store_true', + action="store_true", help="do not save a grid, only individual samples. Helpful when evaluating lots of samples", ) parser.add_argument( "--skip_save", - action='store_true', + action="store_true", help="do not save individual samples. For speed measurements.", ) parser.add_argument( @@ -80,22 +77,22 @@ def main(): ) parser.add_argument( "--plms", - action='store_true', + action="store_true", help="use plms sampling", ) parser.add_argument( "--klms", - action='store_true', + action="store_true", help="use klms sampling", ) parser.add_argument( "--laion400m", - action='store_true', + action="store_true", help="uses the LAION400M model", ) parser.add_argument( "--fixed_code", - action='store_true', + action="store_true", help="if enabled, uses the same starting code across samples ", ) parser.add_argument( @@ -176,11 +173,7 @@ def main(): help="the seed (for reproducible sampling)", ) parser.add_argument( - "--precision", - type=str, - help="evaluate at this precision", - choices=["full", "autocast"], - default="autocast" + "--precision", type=str, help="evaluate at this precision", choices=["full", "autocast"], default="autocast" ) opt = parser.parse_args() @@ -190,17 +183,17 @@ def main(): opt.ckpt = "models/ldm/text2img-large/model.ckpt" opt.outdir = "outputs/txt2img-samples-laion400m" - config = OmegaConf.load(f"{opt.config}") model = load_model_from_config(config, f"{opt.ckpt}") seed_everything(opt.seed) device = torch.device(choose_torch_device()) - model = model.to(device) + model = model.to(device) - #for klms + # for klms model_wrap = K.external.CompVisDenoiser(model) + class CFGDenoiser(nn.Module): def __init__(self, model): super().__init__() @@ -232,10 +225,10 @@ def main(): print(f"reading prompts from {opt.from_file}") with open(opt.from_file, "r") as f: data = f.read().splitlines() - if (len(data) >= batch_size): + if len(data) >= batch_size: data = list(chunk(data, batch_size)) else: - while (len(data) < batch_size): + while len(data) < batch_size: data.append(data[-1]) data = [data] @@ -247,14 +240,14 @@ def main(): start_code = None if opt.fixed_code: shape = [opt.n_samples, opt.C, opt.H // opt.f, opt.W // opt.f] - if device.type == 'mps': - start_code = torch.randn(shape, device='cpu').to(device) + if device.type == "mps": + start_code = torch.randn(shape, device="cpu").to(device) else: torch.randn(shape, device=device) - precision_scope = autocast if opt.precision=="autocast" else nullcontext - if device.type in ['mps', 'cpu']: - precision_scope = nullcontext # have to use f32 on mps + precision_scope = autocast if opt.precision == "autocast" else nullcontext + if device.type in ["mps", "cpu"]: + precision_scope = nullcontext # have to use f32 on mps with torch.no_grad(): with precision_scope(device.type): with model.ema_scope(): @@ -271,23 +264,25 @@ def main(): shape = [opt.C, opt.H // opt.f, opt.W // opt.f] if not opt.klms: - samples_ddim, _ = sampler.sample(S=opt.ddim_steps, - conditioning=c, - batch_size=opt.n_samples, - shape=shape, - verbose=False, - unconditional_guidance_scale=opt.scale, - unconditional_conditioning=uc, - eta=opt.ddim_eta, - x_T=start_code) + samples_ddim, _ = sampler.sample( + S=opt.ddim_steps, + conditioning=c, + batch_size=opt.n_samples, + shape=shape, + verbose=False, + unconditional_guidance_scale=opt.scale, + unconditional_conditioning=uc, + eta=opt.ddim_eta, + x_T=start_code, + ) else: sigmas = model_wrap.get_sigmas(opt.ddim_steps) if start_code: x = start_code else: - x = torch.randn([opt.n_samples, *shape], device=device) * sigmas[0] # for GPU draw + x = torch.randn([opt.n_samples, *shape], device=device) * sigmas[0] # for GPU draw model_wrap_cfg = CFGDenoiser(model_wrap) - extra_args = {'cond': c, 'uncond': uc, 'cond_scale': opt.scale} + extra_args = {"cond": c, "uncond": uc, "cond_scale": opt.scale} samples_ddim = K.sampling.sample_lms(model_wrap_cfg, x, sigmas, extra_args=extra_args) x_samples_ddim = model.decode_first_stage(samples_ddim) @@ -295,9 +290,10 @@ def main(): if not opt.skip_save: for x_sample in x_samples_ddim: - x_sample = 255. * rearrange(x_sample.cpu().numpy(), 'c h w -> h w c') + x_sample = 255.0 * rearrange(x_sample.cpu().numpy(), "c h w -> h w c") Image.fromarray(x_sample.astype(np.uint8)).save( - os.path.join(sample_path, f"{base_count:05}.png")) + os.path.join(sample_path, f"{base_count:05}.png") + ) base_count += 1 if not opt.skip_grid: @@ -306,18 +302,17 @@ def main(): if not opt.skip_grid: # additionally, save as grid grid = torch.stack(all_samples, 0) - grid = rearrange(grid, 'n b c h w -> (n b) c h w') + grid = rearrange(grid, "n b c h w -> (n b) c h w") grid = make_grid(grid, nrow=n_rows) # to image - grid = 255. * rearrange(grid, 'c h w -> h w c').cpu().numpy() - Image.fromarray(grid.astype(np.uint8)).save(os.path.join(outpath, f'grid-{grid_count:04}.png')) + grid = 255.0 * rearrange(grid, "c h w -> h w c").cpu().numpy() + Image.fromarray(grid.astype(np.uint8)).save(os.path.join(outpath, f"grid-{grid_count:04}.png")) grid_count += 1 toc = time.time() - print(f"Your samples are ready and waiting for you here: \n{outpath} \n" - f" \nEnjoy.") + print(f"Your samples are ready and waiting for you here: \n{outpath} \n" f" \nEnjoy.") if __name__ == "__main__": diff --git a/scripts/probe-model.py b/scripts/probe-model.py new file mode 100755 index 0000000000..7281dafc3f --- /dev/null +++ b/scripts/probe-model.py @@ -0,0 +1,16 @@ +#!/bin/env python + +import argparse +import sys +from pathlib import Path +from invokeai.backend.model_management.model_probe import ModelProbe + +parser = argparse.ArgumentParser(description="Probe model type") +parser.add_argument( + "model_path", + type=Path, +) +args = parser.parse_args() + +info = ModelProbe().probe(args.model_path) +print(info) diff --git a/scripts/pypi_helper.py b/scripts/pypi_helper.py index 4dccd6383d..6c1f9b9033 100755 --- a/scripts/pypi_helper.py +++ b/scripts/pypi_helper.py @@ -5,7 +5,8 @@ import requests from invokeai.version import __version__ local_version = str(__version__).replace("-", "") -package_name = 'InvokeAI' +package_name = "InvokeAI" + def get_pypi_versions(package_name=package_name) -> list[str]: """Get the versions of the package from PyPI""" diff --git a/scripts/scan_models_directory.py b/scripts/scan_models_directory.py index 778a6c5ed5..de7278f5b7 100755 --- a/scripts/scan_models_directory.py +++ b/scripts/scan_models_directory.py @@ -1,8 +1,8 @@ #!/usr/bin/env python -''' +""" Scan the models directory and print out a new models.yaml -''' +""" import os import sys @@ -11,49 +11,51 @@ import argparse from pathlib import Path from omegaconf import OmegaConf + def main(): parser = argparse.ArgumentParser(description="Model directory scanner") - parser.add_argument('models_directory') - parser.add_argument('--all-models', - default=False, - action='store_true', - help='If true, then generates stanzas for all models; otherwise just diffusers' - ) - + parser.add_argument("models_directory") + parser.add_argument( + "--all-models", + default=False, + action="store_true", + help="If true, then generates stanzas for all models; otherwise just diffusers", + ) + args = parser.parse_args() directory = args.models_directory conf = OmegaConf.create() - conf['_version'] = '3.0.0' - + conf["_version"] = "3.0.0" + for root, dirs, files in os.walk(directory): - parents = root.split('/') - subpaths = parents[parents.index('models')+1:] + parents = root.split("/") + subpaths = parents[parents.index("models") + 1 :] if len(subpaths) < 2: continue base, model_type, *_ = subpaths - - if args.all_models or model_type=='diffusers': + + if args.all_models or model_type == "diffusers": for d in dirs: - conf[f'{base}/{model_type}/{d}'] = dict( - path = os.path.join(root,d), - description = f'{model_type} model {d}', - format = 'folder', - base = base, + conf[f"{base}/{model_type}/{d}"] = dict( + path=os.path.join(root, d), + description=f"{model_type} model {d}", + format="folder", + base=base, ) for f in files: basename = Path(f).stem format = Path(f).suffix[1:] - conf[f'{base}/{model_type}/{basename}'] = dict( - path = os.path.join(root,f), - description = f'{model_type} model {basename}', - format = format, - base = base, + conf[f"{base}/{model_type}/{basename}"] = dict( + path=os.path.join(root, f), + description=f"{model_type} model {basename}", + format=format, + base=base, ) - - OmegaConf.save(config=dict(sorted(conf.items())), f=sys.stdout) - -if __name__ == '__main__': + OmegaConf.save(config=dict(sorted(conf.items())), f=sys.stdout) + + +if __name__ == "__main__": main() diff --git a/scripts/sd-metadata.py b/scripts/sd-metadata.py index 6f9c73757d..1a27e73d95 100755 --- a/scripts/sd-metadata.py +++ b/scripts/sd-metadata.py @@ -13,10 +13,10 @@ filenames = sys.argv[1:] for f in filenames: try: metadata = retrieve_metadata(f) - print(f'{f}:\n',json.dumps(metadata['sd-metadata'], indent=4)) + print(f"{f}:\n", json.dumps(metadata["sd-metadata"], indent=4)) except FileNotFoundError: - sys.stderr.write(f'{f} not found\n') + sys.stderr.write(f"{f} not found\n") continue except PermissionError: - sys.stderr.write(f'{f} could not be opened due to inadequate permissions\n') + sys.stderr.write(f"{f} could not be opened due to inadequate permissions\n") continue diff --git a/tests/nodes/test_graph_execution_state.py b/tests/nodes/test_graph_execution_state.py index bc4a3f4176..e0ee120b54 100644 --- a/tests/nodes/test_graph_execution_state.py +++ b/tests/nodes/test_graph_execution_state.py @@ -42,26 +42,24 @@ def simple_graph(): def mock_services() -> InvocationServices: # NOTE: none of these are actually called by the test invocations return InvocationServices( - model_manager = None, # type: ignore - events = TestEventService(), - logger = None, # type: ignore - images = None, # type: ignore - latents = None, # type: ignore - boards = None, # type: ignore - board_images = None, # type: ignore - queue = MemoryInvocationQueue(), - graph_library=SqliteItemStorage[LibraryGraph]( - filename=sqlite_memory, table_name="graphs" + model_manager=None, # type: ignore + events=TestEventService(), + logger=None, # type: ignore + images=None, # type: ignore + latents=None, # type: ignore + boards=None, # type: ignore + board_images=None, # type: ignore + queue=MemoryInvocationQueue(), + graph_library=SqliteItemStorage[LibraryGraph](filename=sqlite_memory, table_name="graphs"), + graph_execution_manager=SqliteItemStorage[GraphExecutionState]( + filename=sqlite_memory, table_name="graph_executions" ), - graph_execution_manager = SqliteItemStorage[GraphExecutionState](filename = sqlite_memory, table_name = 'graph_executions'), - processor = DefaultInvocationProcessor(), - configuration = None, # type: ignore + processor=DefaultInvocationProcessor(), + configuration=None, # type: ignore ) -def invoke_next( - g: GraphExecutionState, services: InvocationServices -) -> tuple[BaseInvocation, BaseInvocationOutput]: +def invoke_next(g: GraphExecutionState, services: InvocationServices) -> tuple[BaseInvocation, BaseInvocationOutput]: n = g.next() if n is None: return (None, None) @@ -130,9 +128,7 @@ def test_graph_state_expands_iterator(mock_services): def test_graph_state_collects(mock_services): graph = Graph() test_prompts = ["Banana sushi", "Cat sushi"] - graph.add_node( - PromptCollectionTestInvocation(id="1", collection=list(test_prompts)) - ) + graph.add_node(PromptCollectionTestInvocation(id="1", collection=list(test_prompts))) graph.add_node(IterateInvocation(id="2")) graph.add_node(PromptTestInvocation(id="3")) graph.add_node(CollectInvocation(id="4")) @@ -158,16 +154,10 @@ def test_graph_state_prepares_eagerly(mock_services): graph = Graph() test_prompts = ["Banana sushi", "Cat sushi"] - graph.add_node( - PromptCollectionTestInvocation( - id="prompt_collection", collection=list(test_prompts) - ) - ) + graph.add_node(PromptCollectionTestInvocation(id="prompt_collection", collection=list(test_prompts))) graph.add_node(IterateInvocation(id="iterate")) graph.add_node(PromptTestInvocation(id="prompt_iterated")) - graph.add_edge( - create_edge("prompt_collection", "collection", "iterate", "collection") - ) + graph.add_edge(create_edge("prompt_collection", "collection", "iterate", "collection")) graph.add_edge(create_edge("iterate", "item", "prompt_iterated", "prompt")) # separated, fully-preparable chain of nodes @@ -193,21 +183,13 @@ def test_graph_executes_depth_first(mock_services): graph = Graph() test_prompts = ["Banana sushi", "Cat sushi"] - graph.add_node( - PromptCollectionTestInvocation( - id="prompt_collection", collection=list(test_prompts) - ) - ) + graph.add_node(PromptCollectionTestInvocation(id="prompt_collection", collection=list(test_prompts))) graph.add_node(IterateInvocation(id="iterate")) graph.add_node(PromptTestInvocation(id="prompt_iterated")) graph.add_node(PromptTestInvocation(id="prompt_successor")) - graph.add_edge( - create_edge("prompt_collection", "collection", "iterate", "collection") - ) + graph.add_edge(create_edge("prompt_collection", "collection", "iterate", "collection")) graph.add_edge(create_edge("iterate", "item", "prompt_iterated", "prompt")) - graph.add_edge( - create_edge("prompt_iterated", "prompt", "prompt_successor", "prompt") - ) + graph.add_edge(create_edge("prompt_iterated", "prompt", "prompt_successor", "prompt")) g = GraphExecutionState(graph=graph) n1 = invoke_next(g, mock_services) diff --git a/tests/nodes/test_invoker.py b/tests/nodes/test_invoker.py index 4741e7f58b..8eba6d468f 100644 --- a/tests/nodes/test_invoker.py +++ b/tests/nodes/test_invoker.py @@ -35,20 +35,20 @@ def simple_graph(): def mock_services() -> InvocationServices: # NOTE: none of these are actually called by the test invocations return InvocationServices( - model_manager = None, # type: ignore - events = TestEventService(), - logger = None, # type: ignore - images = None, # type: ignore - latents = None, # type: ignore - boards = None, # type: ignore - board_images = None, # type: ignore - queue = MemoryInvocationQueue(), - graph_library=SqliteItemStorage[LibraryGraph]( - filename=sqlite_memory, table_name="graphs" + model_manager=None, # type: ignore + events=TestEventService(), + logger=None, # type: ignore + images=None, # type: ignore + latents=None, # type: ignore + boards=None, # type: ignore + board_images=None, # type: ignore + queue=MemoryInvocationQueue(), + graph_library=SqliteItemStorage[LibraryGraph](filename=sqlite_memory, table_name="graphs"), + graph_execution_manager=SqliteItemStorage[GraphExecutionState]( + filename=sqlite_memory, table_name="graph_executions" ), - graph_execution_manager = SqliteItemStorage[GraphExecutionState](filename = sqlite_memory, table_name = 'graph_executions'), - processor = DefaultInvocationProcessor(), - configuration = None, # type: ignore + processor=DefaultInvocationProcessor(), + configuration=None, # type: ignore ) diff --git a/tests/nodes/test_node_graph.py b/tests/nodes/test_node_graph.py index e2a4c8b343..0f893cb14c 100644 --- a/tests/nodes/test_node_graph.py +++ b/tests/nodes/test_node_graph.py @@ -1,5 +1,21 @@ -from .test_nodes import ImageToImageTestInvocation, TextToImageTestInvocation, ListPassThroughInvocation, PromptTestInvocation -from invokeai.app.services.graph import Edge, Graph, GraphInvocation, InvalidEdgeError, NodeAlreadyInGraphError, NodeNotFoundError, are_connections_compatible, EdgeConnection, CollectInvocation, IterateInvocation +from .test_nodes import ( + ImageToImageTestInvocation, + TextToImageTestInvocation, + ListPassThroughInvocation, + PromptTestInvocation, +) +from invokeai.app.services.graph import ( + Edge, + Graph, + GraphInvocation, + InvalidEdgeError, + NodeAlreadyInGraphError, + NodeNotFoundError, + are_connections_compatible, + EdgeConnection, + CollectInvocation, + IterateInvocation, +) from invokeai.app.invocations.upscale import ESRGANInvocation from invokeai.app.invocations.image import * from invokeai.app.invocations.math import AddInvocation, SubtractInvocation @@ -11,35 +27,38 @@ import pytest # Helpers def create_edge(from_id: str, from_field: str, to_id: str, to_field: str) -> Edge: return Edge( - source=EdgeConnection(node_id = from_id, field = from_field), - destination=EdgeConnection(node_id = to_id, field = to_field) + source=EdgeConnection(node_id=from_id, field=from_field), + destination=EdgeConnection(node_id=to_id, field=to_field), ) + # Tests def test_connections_are_compatible(): - from_node = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") + from_node = TextToImageTestInvocation(id="1", prompt="Banana sushi") from_field = "image" - to_node = ESRGANInvocation(id = "2") + to_node = ESRGANInvocation(id="2") to_field = "image" result = are_connections_compatible(from_node, from_field, to_node, to_field) assert result == True + def test_connections_are_incompatible(): - from_node = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") + from_node = TextToImageTestInvocation(id="1", prompt="Banana sushi") from_field = "image" - to_node = ESRGANInvocation(id = "2") + to_node = ESRGANInvocation(id="2") to_field = "strength" result = are_connections_compatible(from_node, from_field, to_node, to_field) assert result == False + def test_connections_incompatible_with_invalid_fields(): - from_node = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") + from_node = TextToImageTestInvocation(id="1", prompt="Banana sushi") from_field = "invalid_field" - to_node = ESRGANInvocation(id = "2") + to_node = ESRGANInvocation(id="2") to_field = "image" # From field is invalid @@ -53,138 +72,152 @@ def test_connections_incompatible_with_invalid_fields(): result = are_connections_compatible(from_node, from_field, to_node, to_field) assert result == False + def test_graph_can_add_node(): g = Graph() - n = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") + n = TextToImageTestInvocation(id="1", prompt="Banana sushi") g.add_node(n) assert n.id in g.nodes + def test_graph_fails_to_add_node_with_duplicate_id(): g = Graph() - n = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") + n = TextToImageTestInvocation(id="1", prompt="Banana sushi") g.add_node(n) - n2 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi the second") + n2 = TextToImageTestInvocation(id="1", prompt="Banana sushi the second") with pytest.raises(NodeAlreadyInGraphError): g.add_node(n2) + def test_graph_updates_node(): g = Graph() - n = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") + n = TextToImageTestInvocation(id="1", prompt="Banana sushi") g.add_node(n) - n2 = TextToImageTestInvocation(id = "2", prompt = "Banana sushi the second") + n2 = TextToImageTestInvocation(id="2", prompt="Banana sushi the second") g.add_node(n2) - nu = TextToImageTestInvocation(id = "1", prompt = "Banana sushi updated") + nu = TextToImageTestInvocation(id="1", prompt="Banana sushi updated") g.update_node("1", nu) assert g.nodes["1"].prompt == "Banana sushi updated" + def test_graph_fails_to_update_node_if_type_changes(): g = Graph() - n = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") + n = TextToImageTestInvocation(id="1", prompt="Banana sushi") g.add_node(n) - n2 = ESRGANInvocation(id = "2") + n2 = ESRGANInvocation(id="2") g.add_node(n2) - nu = ESRGANInvocation(id = "1") + nu = ESRGANInvocation(id="1") with pytest.raises(TypeError): g.update_node("1", nu) + def test_graph_allows_non_conflicting_id_change(): g = Graph() - n = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") + n = TextToImageTestInvocation(id="1", prompt="Banana sushi") g.add_node(n) - n2 = ESRGANInvocation(id = "2") + n2 = ESRGANInvocation(id="2") g.add_node(n2) - e1 = create_edge(n.id,"image",n2.id,"image") + e1 = create_edge(n.id, "image", n2.id, "image") g.add_edge(e1) - - nu = TextToImageTestInvocation(id = "3", prompt = "Banana sushi") + + nu = TextToImageTestInvocation(id="3", prompt="Banana sushi") g.update_node("1", nu) with pytest.raises(NodeNotFoundError): g.get_node("1") - + assert g.get_node("3").prompt == "Banana sushi" assert len(g.edges) == 1 - assert Edge(source=EdgeConnection(node_id = "3", field = "image"), destination=EdgeConnection(node_id = "2", field = "image")) in g.edges + assert ( + Edge(source=EdgeConnection(node_id="3", field="image"), destination=EdgeConnection(node_id="2", field="image")) + in g.edges + ) + def test_graph_fails_to_update_node_id_if_conflict(): g = Graph() - n = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") + n = TextToImageTestInvocation(id="1", prompt="Banana sushi") g.add_node(n) - n2 = TextToImageTestInvocation(id = "2", prompt = "Banana sushi the second") + n2 = TextToImageTestInvocation(id="2", prompt="Banana sushi the second") g.add_node(n2) - - nu = TextToImageTestInvocation(id = "2", prompt = "Banana sushi") + + nu = TextToImageTestInvocation(id="2", prompt="Banana sushi") with pytest.raises(NodeAlreadyInGraphError): g.update_node("1", nu) + def test_graph_adds_edge(): g = Graph() - n1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") - n2 = ESRGANInvocation(id = "2") + n1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") + n2 = ESRGANInvocation(id="2") g.add_node(n1) g.add_node(n2) - e = create_edge(n1.id,"image",n2.id,"image") + e = create_edge(n1.id, "image", n2.id, "image") g.add_edge(e) assert e in g.edges + def test_graph_fails_to_add_edge_with_cycle(): g = Graph() - n1 = ESRGANInvocation(id = "1") + n1 = ESRGANInvocation(id="1") g.add_node(n1) - e = create_edge(n1.id,"image",n1.id,"image") + e = create_edge(n1.id, "image", n1.id, "image") with pytest.raises(InvalidEdgeError): g.add_edge(e) + def test_graph_fails_to_add_edge_with_long_cycle(): g = Graph() - n1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") - n2 = ESRGANInvocation(id = "2") - n3 = ESRGANInvocation(id = "3") + n1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") + n2 = ESRGANInvocation(id="2") + n3 = ESRGANInvocation(id="3") g.add_node(n1) g.add_node(n2) g.add_node(n3) - e1 = create_edge(n1.id,"image",n2.id,"image") - e2 = create_edge(n2.id,"image",n3.id,"image") - e3 = create_edge(n3.id,"image",n2.id,"image") + e1 = create_edge(n1.id, "image", n2.id, "image") + e2 = create_edge(n2.id, "image", n3.id, "image") + e3 = create_edge(n3.id, "image", n2.id, "image") g.add_edge(e1) g.add_edge(e2) with pytest.raises(InvalidEdgeError): g.add_edge(e3) + def test_graph_fails_to_add_edge_with_missing_node_id(): g = Graph() - n1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") - n2 = ESRGANInvocation(id = "2") + n1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") + n2 = ESRGANInvocation(id="2") g.add_node(n1) g.add_node(n2) - e1 = create_edge("1","image","3","image") - e2 = create_edge("3","image","1","image") + e1 = create_edge("1", "image", "3", "image") + e2 = create_edge("3", "image", "1", "image") with pytest.raises(InvalidEdgeError): g.add_edge(e1) with pytest.raises(InvalidEdgeError): g.add_edge(e2) + def test_graph_fails_to_add_edge_when_destination_exists(): g = Graph() - n1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") - n2 = ESRGANInvocation(id = "2") - n3 = ESRGANInvocation(id = "3") + n1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") + n2 = ESRGANInvocation(id="2") + n3 = ESRGANInvocation(id="3") g.add_node(n1) g.add_node(n2) g.add_node(n3) - e1 = create_edge(n1.id,"image",n2.id,"image") - e2 = create_edge(n1.id,"image",n3.id,"image") - e3 = create_edge(n2.id,"image",n3.id,"image") + e1 = create_edge(n1.id, "image", n2.id, "image") + e2 = create_edge(n1.id, "image", n3.id, "image") + e3 = create_edge(n2.id, "image", n3.id, "image") g.add_edge(e1) g.add_edge(e2) with pytest.raises(InvalidEdgeError): @@ -193,208 +226,223 @@ def test_graph_fails_to_add_edge_when_destination_exists(): def test_graph_fails_to_add_edge_with_mismatched_types(): g = Graph() - n1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") - n2 = ESRGANInvocation(id = "2") + n1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") + n2 = ESRGANInvocation(id="2") g.add_node(n1) g.add_node(n2) - e1 = create_edge("1","image","2","strength") + e1 = create_edge("1", "image", "2", "strength") with pytest.raises(InvalidEdgeError): g.add_edge(e1) + def test_graph_connects_collector(): g = Graph() - n1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") - n2 = TextToImageTestInvocation(id = "2", prompt = "Banana sushi 2") - n3 = CollectInvocation(id = "3") - n4 = ListPassThroughInvocation(id = "4") + n1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") + n2 = TextToImageTestInvocation(id="2", prompt="Banana sushi 2") + n3 = CollectInvocation(id="3") + n4 = ListPassThroughInvocation(id="4") g.add_node(n1) g.add_node(n2) g.add_node(n3) g.add_node(n4) - e1 = create_edge("1","image","3","item") - e2 = create_edge("2","image","3","item") - e3 = create_edge("3","collection","4","collection") + e1 = create_edge("1", "image", "3", "item") + e2 = create_edge("2", "image", "3", "item") + e3 = create_edge("3", "collection", "4", "collection") g.add_edge(e1) g.add_edge(e2) g.add_edge(e3) + # TODO: test that derived types mixed with base types are compatible + def test_graph_collector_invalid_with_varying_input_types(): g = Graph() - n1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") - n2 = PromptTestInvocation(id = "2", prompt = "banana sushi 2") - n3 = CollectInvocation(id = "3") + n1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") + n2 = PromptTestInvocation(id="2", prompt="banana sushi 2") + n3 = CollectInvocation(id="3") g.add_node(n1) g.add_node(n2) g.add_node(n3) - e1 = create_edge("1","image","3","item") - e2 = create_edge("2","prompt","3","item") + e1 = create_edge("1", "image", "3", "item") + e2 = create_edge("2", "prompt", "3", "item") g.add_edge(e1) - + with pytest.raises(InvalidEdgeError): g.add_edge(e2) + def test_graph_collector_invalid_with_varying_input_output(): g = Graph() - n1 = PromptTestInvocation(id = "1", prompt = "Banana sushi") - n2 = PromptTestInvocation(id = "2", prompt = "Banana sushi 2") - n3 = CollectInvocation(id = "3") - n4 = ListPassThroughInvocation(id = "4") + n1 = PromptTestInvocation(id="1", prompt="Banana sushi") + n2 = PromptTestInvocation(id="2", prompt="Banana sushi 2") + n3 = CollectInvocation(id="3") + n4 = ListPassThroughInvocation(id="4") g.add_node(n1) g.add_node(n2) g.add_node(n3) g.add_node(n4) - e1 = create_edge("1","prompt","3","item") - e2 = create_edge("2","prompt","3","item") - e3 = create_edge("3","collection","4","collection") + e1 = create_edge("1", "prompt", "3", "item") + e2 = create_edge("2", "prompt", "3", "item") + e3 = create_edge("3", "collection", "4", "collection") g.add_edge(e1) g.add_edge(e2) with pytest.raises(InvalidEdgeError): g.add_edge(e3) + def test_graph_collector_invalid_with_non_list_output(): g = Graph() - n1 = PromptTestInvocation(id = "1", prompt = "Banana sushi") - n2 = PromptTestInvocation(id = "2", prompt = "Banana sushi 2") - n3 = CollectInvocation(id = "3") - n4 = PromptTestInvocation(id = "4") + n1 = PromptTestInvocation(id="1", prompt="Banana sushi") + n2 = PromptTestInvocation(id="2", prompt="Banana sushi 2") + n3 = CollectInvocation(id="3") + n4 = PromptTestInvocation(id="4") g.add_node(n1) g.add_node(n2) g.add_node(n3) g.add_node(n4) - e1 = create_edge("1","prompt","3","item") - e2 = create_edge("2","prompt","3","item") - e3 = create_edge("3","collection","4","prompt") + e1 = create_edge("1", "prompt", "3", "item") + e2 = create_edge("2", "prompt", "3", "item") + e3 = create_edge("3", "collection", "4", "prompt") g.add_edge(e1) g.add_edge(e2) with pytest.raises(InvalidEdgeError): g.add_edge(e3) + def test_graph_connects_iterator(): g = Graph() - n1 = ListPassThroughInvocation(id = "1") - n2 = IterateInvocation(id = "2") - n3 = ImageToImageTestInvocation(id = "3", prompt = "Banana sushi") + n1 = ListPassThroughInvocation(id="1") + n2 = IterateInvocation(id="2") + n3 = ImageToImageTestInvocation(id="3", prompt="Banana sushi") g.add_node(n1) g.add_node(n2) g.add_node(n3) - e1 = create_edge("1","collection","2","collection") - e2 = create_edge("2","item","3","image") + e1 = create_edge("1", "collection", "2", "collection") + e2 = create_edge("2", "item", "3", "image") g.add_edge(e1) g.add_edge(e2) + # TODO: TEST INVALID ITERATOR SCENARIOS + def test_graph_iterator_invalid_if_multiple_inputs(): g = Graph() - n1 = ListPassThroughInvocation(id = "1") - n2 = IterateInvocation(id = "2") - n3 = ImageToImageTestInvocation(id = "3", prompt = "Banana sushi") - n4 = ListPassThroughInvocation(id = "4") + n1 = ListPassThroughInvocation(id="1") + n2 = IterateInvocation(id="2") + n3 = ImageToImageTestInvocation(id="3", prompt="Banana sushi") + n4 = ListPassThroughInvocation(id="4") g.add_node(n1) g.add_node(n2) g.add_node(n3) g.add_node(n4) - e1 = create_edge("1","collection","2","collection") - e2 = create_edge("2","item","3","image") - e3 = create_edge("4","collection","2","collection") + e1 = create_edge("1", "collection", "2", "collection") + e2 = create_edge("2", "item", "3", "image") + e3 = create_edge("4", "collection", "2", "collection") g.add_edge(e1) g.add_edge(e2) with pytest.raises(InvalidEdgeError): g.add_edge(e3) + def test_graph_iterator_invalid_if_input_not_list(): g = Graph() - n1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") - n2 = IterateInvocation(id = "2") + n1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") + n2 = IterateInvocation(id="2") g.add_node(n1) g.add_node(n2) - e1 = create_edge("1","collection","2","collection") + e1 = create_edge("1", "collection", "2", "collection") with pytest.raises(InvalidEdgeError): g.add_edge(e1) + def test_graph_iterator_invalid_if_output_and_input_types_different(): g = Graph() - n1 = ListPassThroughInvocation(id = "1") - n2 = IterateInvocation(id = "2") - n3 = PromptTestInvocation(id = "3", prompt = "Banana sushi") + n1 = ListPassThroughInvocation(id="1") + n2 = IterateInvocation(id="2") + n3 = PromptTestInvocation(id="3", prompt="Banana sushi") g.add_node(n1) g.add_node(n2) g.add_node(n3) - e1 = create_edge("1","collection","2","collection") - e2 = create_edge("2","item","3","prompt") + e1 = create_edge("1", "collection", "2", "collection") + e2 = create_edge("2", "item", "3", "prompt") g.add_edge(e1) with pytest.raises(InvalidEdgeError): g.add_edge(e2) + def test_graph_validates(): g = Graph() - n1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") - n2 = ESRGANInvocation(id = "2") + n1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") + n2 = ESRGANInvocation(id="2") g.add_node(n1) g.add_node(n2) - e1 = create_edge("1","image","2","image") + e1 = create_edge("1", "image", "2", "image") g.add_edge(e1) assert g.is_valid() == True + def test_graph_invalid_if_edges_reference_missing_nodes(): g = Graph() - n1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") + n1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") g.nodes[n1.id] = n1 - e1 = create_edge("1","image","2","image") + e1 = create_edge("1", "image", "2", "image") g.edges.append(e1) assert g.is_valid() == False + def test_graph_invalid_if_subgraph_invalid(): g = Graph() - n1 = GraphInvocation(id = "1") + n1 = GraphInvocation(id="1") n1.graph = Graph() - n1_1 = TextToImageTestInvocation(id = "2", prompt = "Banana sushi") + n1_1 = TextToImageTestInvocation(id="2", prompt="Banana sushi") n1.graph.nodes[n1_1.id] = n1_1 - e1 = create_edge("1","image","2","image") + e1 = create_edge("1", "image", "2", "image") n1.graph.edges.append(e1) g.nodes[n1.id] = n1 assert g.is_valid() == False + def test_graph_invalid_if_has_cycle(): g = Graph() - n1 = ESRGANInvocation(id = "1") - n2 = ESRGANInvocation(id = "2") + n1 = ESRGANInvocation(id="1") + n2 = ESRGANInvocation(id="2") g.nodes[n1.id] = n1 g.nodes[n2.id] = n2 - e1 = create_edge("1","image","2","image") - e2 = create_edge("2","image","1","image") + e1 = create_edge("1", "image", "2", "image") + e2 = create_edge("2", "image", "1", "image") g.edges.append(e1) g.edges.append(e2) assert g.is_valid() == False + def test_graph_invalid_with_invalid_connection(): g = Graph() - n1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") - n2 = ESRGANInvocation(id = "2") + n1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") + n2 = ESRGANInvocation(id="2") g.nodes[n1.id] = n1 g.nodes[n2.id] = n2 - e1 = create_edge("1","image","2","strength") + e1 = create_edge("1", "image", "2", "strength") g.edges.append(e1) assert g.is_valid() == False @@ -403,47 +451,47 @@ def test_graph_invalid_with_invalid_connection(): # TODO: Subgraph operations def test_graph_gets_subgraph_node(): g = Graph() - n1 = GraphInvocation(id = "1") + n1 = GraphInvocation(id="1") n1.graph = Graph() n1.graph.add_node - n1_1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") + n1_1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") n1.graph.add_node(n1_1) g.add_node(n1) - result = g.get_node('1.1') + result = g.get_node("1.1") assert result is not None - assert result.id == '1' + assert result.id == "1" assert result == n1_1 def test_graph_expands_subgraph(): g = Graph() - n1 = GraphInvocation(id = "1") + n1 = GraphInvocation(id="1") n1.graph = Graph() - n1_1 = AddInvocation(id = "1", a = 1, b = 2) - n1_2 = SubtractInvocation(id = "2", b = 3) + n1_1 = AddInvocation(id="1", a=1, b=2) + n1_2 = SubtractInvocation(id="2", b=3) n1.graph.add_node(n1_1) n1.graph.add_node(n1_2) - n1.graph.add_edge(create_edge("1","a","2","a")) + n1.graph.add_edge(create_edge("1", "a", "2", "a")) g.add_node(n1) - n2 = AddInvocation(id = "2", b = 5) + n2 = AddInvocation(id="2", b=5) g.add_node(n2) - g.add_edge(create_edge("1.2","a","2","a")) + g.add_edge(create_edge("1.2", "a", "2", "a")) dg = g.nx_graph_flat() - assert set(dg.nodes) == set(['1.1', '1.2', '2']) - assert set(dg.edges) == set([('1.1', '1.2'), ('1.2', '2')]) + assert set(dg.nodes) == set(["1.1", "1.2", "2"]) + assert set(dg.edges) == set([("1.1", "1.2"), ("1.2", "2")]) def test_graph_subgraph_t2i(): g = Graph() - n1 = GraphInvocation(id = "1") + n1 = GraphInvocation(id="1") # Get text to image default graph lg = create_text_to_image() @@ -451,28 +499,26 @@ def test_graph_subgraph_t2i(): g.add_node(n1) - n2 = ParamIntInvocation(id = "2", a = 512) - n3 = ParamIntInvocation(id = "3", a = 256) + n2 = ParamIntInvocation(id="2", a=512) + n3 = ParamIntInvocation(id="3", a=256) g.add_node(n2) g.add_node(n3) - g.add_edge(create_edge("2","a","1.width","a")) - g.add_edge(create_edge("3","a","1.height","a")) - - n4 = ShowImageInvocation(id = "4") + g.add_edge(create_edge("2", "a", "1.width", "a")) + g.add_edge(create_edge("3", "a", "1.height", "a")) + + n4 = ShowImageInvocation(id="4") g.add_node(n4) - g.add_edge(create_edge("1.8","image","4","image")) + g.add_edge(create_edge("1.8", "image", "4", "image")) # Validate dg = g.nx_graph_flat() - assert set(dg.nodes) == set(['1.width', '1.height', '1.seed', '1.3', '1.4', '1.5', '1.6', '1.7', '1.8', '2', '3', '4']) - expected_edges = [(f'1.{e.source.node_id}',f'1.{e.destination.node_id}') for e in lg.graph.edges] - expected_edges.extend([ - ('2','1.width'), - ('3','1.height'), - ('1.8','4') - ]) + assert set(dg.nodes) == set( + ["1.width", "1.height", "1.seed", "1.3", "1.4", "1.5", "1.6", "1.7", "1.8", "2", "3", "4"] + ) + expected_edges = [(f"1.{e.source.node_id}", f"1.{e.destination.node_id}") for e in lg.graph.edges] + expected_edges.extend([("2", "1.width"), ("3", "1.height"), ("1.8", "4")]) print(expected_edges) print(list(dg.edges)) assert set(dg.edges) == set(expected_edges) @@ -480,86 +526,90 @@ def test_graph_subgraph_t2i(): def test_graph_fails_to_get_missing_subgraph_node(): g = Graph() - n1 = GraphInvocation(id = "1") + n1 = GraphInvocation(id="1") n1.graph = Graph() n1.graph.add_node - n1_1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") + n1_1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") n1.graph.add_node(n1_1) g.add_node(n1) with pytest.raises(NodeNotFoundError): - result = g.get_node('1.2') + result = g.get_node("1.2") + def test_graph_fails_to_enumerate_non_subgraph_node(): g = Graph() - n1 = GraphInvocation(id = "1") + n1 = GraphInvocation(id="1") n1.graph = Graph() n1.graph.add_node - n1_1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") + n1_1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") n1.graph.add_node(n1_1) g.add_node(n1) - - n2 = ESRGANInvocation(id = "2") + + n2 = ESRGANInvocation(id="2") g.add_node(n2) with pytest.raises(NodeNotFoundError): - result = g.get_node('2.1') + result = g.get_node("2.1") + def test_graph_gets_networkx_graph(): g = Graph() - n1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") - n2 = ESRGANInvocation(id = "2") + n1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") + n2 = ESRGANInvocation(id="2") g.add_node(n1) g.add_node(n2) - e = create_edge(n1.id,"image",n2.id,"image") + e = create_edge(n1.id, "image", n2.id, "image") g.add_edge(e) nxg = g.nx_graph() - assert '1' in nxg.nodes - assert '2' in nxg.nodes - assert ('1','2') in nxg.edges + assert "1" in nxg.nodes + assert "2" in nxg.nodes + assert ("1", "2") in nxg.edges # TODO: Graph serializes and deserializes def test_graph_can_serialize(): g = Graph() - n1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") - n2 = ESRGANInvocation(id = "2") + n1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") + n2 = ESRGANInvocation(id="2") g.add_node(n1) g.add_node(n2) - e = create_edge(n1.id,"image",n2.id,"image") + e = create_edge(n1.id, "image", n2.id, "image") g.add_edge(e) # Not throwing on this line is sufficient json = g.json() + def test_graph_can_deserialize(): g = Graph() - n1 = TextToImageTestInvocation(id = "1", prompt = "Banana sushi") - n2 = ESRGANInvocation(id = "2") + n1 = TextToImageTestInvocation(id="1", prompt="Banana sushi") + n2 = ESRGANInvocation(id="2") g.add_node(n1) g.add_node(n2) - e = create_edge(n1.id,"image",n2.id,"image") + e = create_edge(n1.id, "image", n2.id, "image") g.add_edge(e) json = g.json() g2 = Graph.parse_raw(json) assert g2 is not None - assert g2.nodes['1'] is not None - assert g2.nodes['2'] is not None + assert g2.nodes["1"] is not None + assert g2.nodes["2"] is not None assert len(g2.edges) == 1 - assert g2.edges[0].source.node_id == '1' - assert g2.edges[0].source.field == 'image' - assert g2.edges[0].destination.node_id == '2' - assert g2.edges[0].destination.field == 'image' + assert g2.edges[0].source.node_id == "1" + assert g2.edges[0].source.field == "image" + assert g2.edges[0].destination.node_id == "2" + assert g2.edges[0].destination.field == "image" + def test_graph_can_generate_schema(): # Not throwing on this line is sufficient # NOTE: if this test fails, it's PROBABLY because a new invocation type is breaking schema generation - schema = Graph.schema_json(indent = 2) + schema = Graph.schema_json(indent=2) diff --git a/tests/nodes/test_nodes.py b/tests/nodes/test_nodes.py index af011954c5..13338e9261 100644 --- a/tests/nodes/test_nodes.py +++ b/tests/nodes/test_nodes.py @@ -5,79 +5,92 @@ from invokeai.app.services.invocation_services import InvocationServices from pydantic import Field import pytest + # Define test invocations before importing anything that uses invocations class ListPassThroughInvocationOutput(BaseInvocationOutput): - type: Literal['test_list_output'] = 'test_list_output' + type: Literal["test_list_output"] = "test_list_output" collection: list[ImageField] = Field(default_factory=list) + class ListPassThroughInvocation(BaseInvocation): - type: Literal['test_list'] = 'test_list' + type: Literal["test_list"] = "test_list" collection: list[ImageField] = Field(default_factory=list) def invoke(self, context: InvocationContext) -> ListPassThroughInvocationOutput: - return ListPassThroughInvocationOutput(collection = self.collection) + return ListPassThroughInvocationOutput(collection=self.collection) + class PromptTestInvocationOutput(BaseInvocationOutput): - type: Literal['test_prompt_output'] = 'test_prompt_output' + type: Literal["test_prompt_output"] = "test_prompt_output" + + prompt: str = Field(default="") - prompt: str = Field(default = "") class PromptTestInvocation(BaseInvocation): - type: Literal['test_prompt'] = 'test_prompt' + type: Literal["test_prompt"] = "test_prompt" - prompt: str = Field(default = "") + prompt: str = Field(default="") def invoke(self, context: InvocationContext) -> PromptTestInvocationOutput: - return PromptTestInvocationOutput(prompt = self.prompt) + return PromptTestInvocationOutput(prompt=self.prompt) + class ErrorInvocation(BaseInvocation): - type: Literal['test_error'] = 'test_error' + type: Literal["test_error"] = "test_error" def invoke(self, context: InvocationContext) -> PromptTestInvocationOutput: raise Exception("This invocation is supposed to fail") + class ImageTestInvocationOutput(BaseInvocationOutput): - type: Literal['test_image_output'] = 'test_image_output' + type: Literal["test_image_output"] = "test_image_output" image: ImageField = Field() -class TextToImageTestInvocation(BaseInvocation): - type: Literal['test_text_to_image'] = 'test_text_to_image' - prompt: str = Field(default = "") +class TextToImageTestInvocation(BaseInvocation): + type: Literal["test_text_to_image"] = "test_text_to_image" + + prompt: str = Field(default="") def invoke(self, context: InvocationContext) -> ImageTestInvocationOutput: return ImageTestInvocationOutput(image=ImageField(image_name=self.id)) -class ImageToImageTestInvocation(BaseInvocation): - type: Literal['test_image_to_image'] = 'test_image_to_image' - prompt: str = Field(default = "") +class ImageToImageTestInvocation(BaseInvocation): + type: Literal["test_image_to_image"] = "test_image_to_image" + + prompt: str = Field(default="") image: Union[ImageField, None] = Field(default=None) def invoke(self, context: InvocationContext) -> ImageTestInvocationOutput: return ImageTestInvocationOutput(image=ImageField(image_name=self.id)) + class PromptCollectionTestInvocationOutput(BaseInvocationOutput): - type: Literal['test_prompt_collection_output'] = 'test_prompt_collection_output' + type: Literal["test_prompt_collection_output"] = "test_prompt_collection_output" collection: list[str] = Field(default_factory=list) + class PromptCollectionTestInvocation(BaseInvocation): - type: Literal['test_prompt_collection'] = 'test_prompt_collection' + type: Literal["test_prompt_collection"] = "test_prompt_collection" collection: list[str] = Field() def invoke(self, context: InvocationContext) -> PromptCollectionTestInvocationOutput: return PromptCollectionTestInvocationOutput(collection=self.collection.copy()) + from invokeai.app.services.events import EventServiceBase from invokeai.app.services.graph import Edge, EdgeConnection + def create_edge(from_id: str, from_field: str, to_id: str, to_field: str) -> Edge: return Edge( - source=EdgeConnection(node_id = from_id, field = from_field), - destination=EdgeConnection(node_id = to_id, field = to_field)) + source=EdgeConnection(node_id=from_id, field=from_field), + destination=EdgeConnection(node_id=to_id, field=to_field), + ) class TestEvent: @@ -88,6 +101,7 @@ class TestEvent: self.event_name = event_name self.payload = payload + class TestEventService(EventServiceBase): events: list @@ -98,8 +112,10 @@ class TestEventService(EventServiceBase): def dispatch(self, event_name: str, payload: Any) -> None: pass + def wait_until(condition: Callable[[], bool], timeout: int = 10, interval: float = 0.1) -> None: import time + start_time = time.time() while time.time() - start_time < timeout: if condition(): diff --git a/tests/nodes/test_sqlite.py b/tests/nodes/test_sqlite.py index a803af5635..a9eb542e44 100644 --- a/tests/nodes/test_sqlite.py +++ b/tests/nodes/test_sqlite.py @@ -3,110 +3,131 @@ from pydantic import BaseModel, Field class TestModel(BaseModel): - id: str = Field(description = "ID") - name: str = Field(description = "Name") + id: str = Field(description="ID") + name: str = Field(description="Name") def test_sqlite_service_can_create_and_get(): - db = SqliteItemStorage[TestModel](sqlite_memory, 'test', 'id') - db.set(TestModel(id = '1', name = 'Test')) - assert db.get('1') == TestModel(id = '1', name = 'Test') + db = SqliteItemStorage[TestModel](sqlite_memory, "test", "id") + db.set(TestModel(id="1", name="Test")) + assert db.get("1") == TestModel(id="1", name="Test") + def test_sqlite_service_can_list(): - db = SqliteItemStorage[TestModel](sqlite_memory, 'test', 'id') - db.set(TestModel(id = '1', name = 'Test')) - db.set(TestModel(id = '2', name = 'Test')) - db.set(TestModel(id = '3', name = 'Test')) + db = SqliteItemStorage[TestModel](sqlite_memory, "test", "id") + db.set(TestModel(id="1", name="Test")) + db.set(TestModel(id="2", name="Test")) + db.set(TestModel(id="3", name="Test")) results = db.list() assert results.page == 0 assert results.pages == 1 assert results.per_page == 10 assert results.total == 3 - assert results.items == [TestModel(id = '1', name = 'Test'), TestModel(id = '2', name = 'Test'), TestModel(id = '3', name = 'Test')] + assert results.items == [ + TestModel(id="1", name="Test"), + TestModel(id="2", name="Test"), + TestModel(id="3", name="Test"), + ] + def test_sqlite_service_can_delete(): - db = SqliteItemStorage[TestModel](sqlite_memory, 'test', 'id') - db.set(TestModel(id = '1', name = 'Test')) - db.delete('1') - assert db.get('1') is None + db = SqliteItemStorage[TestModel](sqlite_memory, "test", "id") + db.set(TestModel(id="1", name="Test")) + db.delete("1") + assert db.get("1") is None + def test_sqlite_service_calls_set_callback(): - db = SqliteItemStorage[TestModel](sqlite_memory, 'test', 'id') + db = SqliteItemStorage[TestModel](sqlite_memory, "test", "id") called = False + def on_changed(item: TestModel): nonlocal called called = True + db.on_changed(on_changed) - db.set(TestModel(id = '1', name = 'Test')) + db.set(TestModel(id="1", name="Test")) assert called + def test_sqlite_service_calls_delete_callback(): - db = SqliteItemStorage[TestModel](sqlite_memory, 'test', 'id') + db = SqliteItemStorage[TestModel](sqlite_memory, "test", "id") called = False + def on_deleted(item_id: str): nonlocal called called = True + db.on_deleted(on_deleted) - db.set(TestModel(id = '1', name = 'Test')) - db.delete('1') + db.set(TestModel(id="1", name="Test")) + db.delete("1") assert called + def test_sqlite_service_can_list_with_pagination(): - db = SqliteItemStorage[TestModel](sqlite_memory, 'test', 'id') - db.set(TestModel(id = '1', name = 'Test')) - db.set(TestModel(id = '2', name = 'Test')) - db.set(TestModel(id = '3', name = 'Test')) - results = db.list(page = 0, per_page = 2) + db = SqliteItemStorage[TestModel](sqlite_memory, "test", "id") + db.set(TestModel(id="1", name="Test")) + db.set(TestModel(id="2", name="Test")) + db.set(TestModel(id="3", name="Test")) + results = db.list(page=0, per_page=2) assert results.page == 0 assert results.pages == 2 assert results.per_page == 2 assert results.total == 3 - assert results.items == [TestModel(id = '1', name = 'Test'), TestModel(id = '2', name = 'Test')] + assert results.items == [TestModel(id="1", name="Test"), TestModel(id="2", name="Test")] + def test_sqlite_service_can_list_with_pagination_and_offset(): - db = SqliteItemStorage[TestModel](sqlite_memory, 'test', 'id') - db.set(TestModel(id = '1', name = 'Test')) - db.set(TestModel(id = '2', name = 'Test')) - db.set(TestModel(id = '3', name = 'Test')) - results = db.list(page = 1, per_page = 2) + db = SqliteItemStorage[TestModel](sqlite_memory, "test", "id") + db.set(TestModel(id="1", name="Test")) + db.set(TestModel(id="2", name="Test")) + db.set(TestModel(id="3", name="Test")) + results = db.list(page=1, per_page=2) assert results.page == 1 assert results.pages == 2 assert results.per_page == 2 assert results.total == 3 - assert results.items == [TestModel(id = '3', name = 'Test')] + assert results.items == [TestModel(id="3", name="Test")] + def test_sqlite_service_can_search(): - db = SqliteItemStorage[TestModel](sqlite_memory, 'test', 'id') - db.set(TestModel(id = '1', name = 'Test')) - db.set(TestModel(id = '2', name = 'Test')) - db.set(TestModel(id = '3', name = 'Test')) - results = db.search(query = 'Test') + db = SqliteItemStorage[TestModel](sqlite_memory, "test", "id") + db.set(TestModel(id="1", name="Test")) + db.set(TestModel(id="2", name="Test")) + db.set(TestModel(id="3", name="Test")) + results = db.search(query="Test") assert results.page == 0 assert results.pages == 1 assert results.per_page == 10 assert results.total == 3 - assert results.items == [TestModel(id = '1', name = 'Test'), TestModel(id = '2', name = 'Test'), TestModel(id = '3', name = 'Test')] + assert results.items == [ + TestModel(id="1", name="Test"), + TestModel(id="2", name="Test"), + TestModel(id="3", name="Test"), + ] + def test_sqlite_service_can_search_with_pagination(): - db = SqliteItemStorage[TestModel](sqlite_memory, 'test', 'id') - db.set(TestModel(id = '1', name = 'Test')) - db.set(TestModel(id = '2', name = 'Test')) - db.set(TestModel(id = '3', name = 'Test')) - results = db.search(query = 'Test', page = 0, per_page = 2) + db = SqliteItemStorage[TestModel](sqlite_memory, "test", "id") + db.set(TestModel(id="1", name="Test")) + db.set(TestModel(id="2", name="Test")) + db.set(TestModel(id="3", name="Test")) + results = db.search(query="Test", page=0, per_page=2) assert results.page == 0 assert results.pages == 2 assert results.per_page == 2 assert results.total == 3 - assert results.items == [TestModel(id = '1', name = 'Test'), TestModel(id = '2', name = 'Test')] + assert results.items == [TestModel(id="1", name="Test"), TestModel(id="2", name="Test")] + def test_sqlite_service_can_search_with_pagination_and_offset(): - db = SqliteItemStorage[TestModel](sqlite_memory, 'test', 'id') - db.set(TestModel(id = '1', name = 'Test')) - db.set(TestModel(id = '2', name = 'Test')) - db.set(TestModel(id = '3', name = 'Test')) - results = db.search(query = 'Test', page = 1, per_page = 2) + db = SqliteItemStorage[TestModel](sqlite_memory, "test", "id") + db.set(TestModel(id="1", name="Test")) + db.set(TestModel(id="2", name="Test")) + db.set(TestModel(id="3", name="Test")) + results = db.search(query="Test", page=1, per_page=2) assert results.page == 1 assert results.pages == 2 assert results.per_page == 2 assert results.total == 3 - assert results.items == [TestModel(id = '3', name = 'Test')] + assert results.items == [TestModel(id="3", name="Test")] diff --git a/tests/test_config.py b/tests/test_config.py index 498a47748e..5d3dc46aa4 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -5,87 +5,91 @@ import sys from omegaconf import OmegaConf from pathlib import Path -os.environ['INVOKEAI_ROOT']='/tmp' +os.environ["INVOKEAI_ROOT"] = "/tmp" from invokeai.app.services.config import InvokeAIAppConfig init1 = OmegaConf.create( -''' + """ InvokeAI: Features: always_use_cpu: false Memory/Performance: max_cache_size: 5 tiled_decode: false -''' +""" ) init2 = OmegaConf.create( -''' + """ InvokeAI: Features: always_use_cpu: true Memory/Performance: max_cache_size: 2 tiled_decode: true -''' +""" ) + def test_use_init(): # note that we explicitly set omegaconf dict and argv here # so that the values aren't read from ~invokeai/invokeai.yaml and # sys.argv respectively. conf1 = InvokeAIAppConfig.get_config() assert conf1 - conf1.parse_args(conf=init1,argv=[]) + conf1.parse_args(conf=init1, argv=[]) assert not conf1.tiled_decode - assert conf1.max_cache_size==5 + assert conf1.max_cache_size == 5 assert not conf1.always_use_cpu conf2 = InvokeAIAppConfig.get_config() assert conf2 - conf2.parse_args(conf=init2,argv=[]) + conf2.parse_args(conf=init2, argv=[]) assert conf2.tiled_decode - assert conf2.max_cache_size==2 - assert not hasattr(conf2,'invalid_attribute') - + assert conf2.max_cache_size == 2 + assert not hasattr(conf2, "invalid_attribute") + + def test_argv_override(): conf = InvokeAIAppConfig.get_config() - conf.parse_args(conf=init1,argv=['--always_use_cpu','--max_cache=10']) + conf.parse_args(conf=init1, argv=["--always_use_cpu", "--max_cache=10"]) assert conf.always_use_cpu - assert conf.max_cache_size==10 - assert conf.outdir==Path('outputs') # this is the default - + assert conf.max_cache_size == 10 + assert conf.outdir == Path("outputs") # this is the default + + def test_env_override(): - # argv overrides + # argv overrides conf = InvokeAIAppConfig() - conf.parse_args(conf=init1,argv=['--max_cache=10']) - assert conf.always_use_cpu==False - os.environ['INVOKEAI_always_use_cpu'] = 'True' - conf.parse_args(conf=init1,argv=['--max_cache=10']) - assert conf.always_use_cpu==True + conf.parse_args(conf=init1, argv=["--max_cache=10"]) + assert conf.always_use_cpu == False + os.environ["INVOKEAI_always_use_cpu"] = "True" + conf.parse_args(conf=init1, argv=["--max_cache=10"]) + assert conf.always_use_cpu == True # environment variables should be case insensitive - os.environ['InvokeAI_Max_Cache_Size'] = '15' + os.environ["InvokeAI_Max_Cache_Size"] = "15" conf = InvokeAIAppConfig() - conf.parse_args(conf=init1,argv=[]) + conf.parse_args(conf=init1, argv=[]) assert conf.max_cache_size == 15 conf = InvokeAIAppConfig() - conf.parse_args(conf=init1,argv=['--no-always_use_cpu','--max_cache=10']) - assert conf.always_use_cpu==False - assert conf.max_cache_size==10 + conf.parse_args(conf=init1, argv=["--no-always_use_cpu", "--max_cache=10"]) + assert conf.always_use_cpu == False + assert conf.max_cache_size == 10 conf = InvokeAIAppConfig.get_config(max_cache_size=20) - conf.parse_args(conf=init1,argv=[]) - assert conf.max_cache_size==20 + conf.parse_args(conf=init1, argv=[]) + assert conf.max_cache_size == 20 + def test_type_coercion(): conf = InvokeAIAppConfig().get_config() - conf.parse_args(argv=['--root=/tmp/foobar']) - assert conf.root==Path('/tmp/foobar') - assert isinstance(conf.root,Path) - conf = InvokeAIAppConfig.get_config(root='/tmp/different') - conf.parse_args(argv=['--root=/tmp/foobar']) - assert conf.root==Path('/tmp/different') - assert isinstance(conf.root,Path) + conf.parse_args(argv=["--root=/tmp/foobar"]) + assert conf.root == Path("/tmp/foobar") + assert isinstance(conf.root, Path) + conf = InvokeAIAppConfig.get_config(root="/tmp/different") + conf.parse_args(argv=["--root=/tmp/foobar"]) + assert conf.root == Path("/tmp/different") + assert isinstance(conf.root, Path) diff --git a/tests/test_path.py b/tests/test_path.py index 52936142c7..0da5f2f8dc 100644 --- a/tests/test_path.py +++ b/tests/test_path.py @@ -11,6 +11,7 @@ import invokeai.frontend.web.dist as frontend import invokeai.configs as configs import invokeai.app.assets.images as image_assets + class ConfigsTestCase(unittest.TestCase): """Test the configuration related imports and objects"""